a brilliant Perl One liner

Andy Lester posted a link to this article, and this one-liner  is the first in that article:
perl -lne '(1x$_) !~ /^1?$|^(11+?)\1+$/ && print "$_ is prime"'

Can I just say that testing for a prime number with one line of code is brilliant?

And it can run quickly too, the lower the divisor the faster the run time.

The algorithm however has some inefficiencies that will keep you limited to smaller numbers. It will scan to see if the number is a multiple of 2, then it will scan to see if it is a multiple of 3, then it goes on to scan for 4, which will never match because it would have stopped at 2. This inefficiencies of this algorithm cannot be overcome while using a regular expression.

However it is still really neat.


I once wrote a 128-character Perl program to give you a list of the prime numbers in a range. It's not quite as short as the regular expression, but it does work for larger numbers.


I found your blog on google and read a few of your other posts. I just added you to my Google News Reader. Keep up the good work. Look forward to reading more from you in the future.

Thought-provoking entry, kudos for helping keep me occupied in our meeting =)

About this Entry

This page contains a single entry by leonard published on November 13, 2009 9:19 AM.

Frozen Perl Call for speakers was the previous entry in this blog.

Long busy week is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.