1) The regex works because of backtracking. Perl's regular expressions *want* to match, and they keep trying until they've exhausted every possibility that will let them match.

Once you understand that, you'll understand why it "doesn't" match the whole string in $_. I say "doesn't" because you're right, in a sense--the pattern *does* match the entire string. But then it moves on to the next part of the regex (the \1+) and sees that, if the first part matches the entire string, there's nothing left for the \1+ to match. So the regex wouldn't match.

So the matcher moves back one x in the string, and tries to match again; and it keeps moving backwards (backtracking) through the string until it finds a match. If it doesn't find a match, the match fails, and you have a prime--because there is no pattern such that the pattern repeated a certain number of times matches the string; and since the string is x repeated N number of times, this means that there is no number such that the number times another number equals the original number. That sounded confusing--I suppose that's why symbolic notation was invented. :)

For more on backtracking, look in perlre.

2) \1 is used because \1 is used "inside" of a pattern (on the left-hand side of a substitution operator, or inside a matching operator); you use $1 "outside" of a pattern (on the right-hand side of a substitution operator, or outside a matching operator). More in perlre.


In reply to RE: RE: RE: RE: Primes by btrott
in thread Primes by Mo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.