ALL


  A Perl Regular Expression That Matches Prime Numbers

perl -lne '(1x$_) =~ /^1?$|^(11+?)\1+$/ || print "$_ is prime"'Can you figure out how it works? I give an explanation below, but try to figure it out yourself. Here is what happens when you run it:$ perl -lne '(1x$_) =~ /^1?$|^(11+?)\1+$/ || print "$_ is prime"'122 is prime33 is prime455 is prime677 is prime89101111 is primeHere is how it works.First, the number is converted in its unary representation by (1x$_). For example, the number 5 gets converted into 1x5, which is 11111 (1 repeated 5 times.)Next, the unary string gets tested against the regular expression. If it matches, the number is ...

5,624 0       REGULAR EXPRESSION PERL REGEX PRIME NUMBER ONE LINE