Perl implementation using the more-efficient algorithm