1. Why the (xx+) part does not match the entire string.
Used on its own, it would. The thing is that when it is combined with \1+ in the regex: /(xx+)\1+/,
it is now requred to match 2 or more x's followed by 1 or more of the same number of x's again.
Which just doesn't work if (xx+) gobbles all the x's to start with!
It still is greedy, in that 6x's will match as xxx and xxx rather than xx and 2 lots of xx, but it can't be TOO greedy or the match doesn't work.
2. Why $1 is not exactly the same as \1
As with most things in Perl, these two are kinda the same but not identical.
$1 is actually what was matched in the LAST pattern match and \1 is a backreference which only works within the CURRENT pattern match.
If you use \1 outside of a regexp you are likely to just get a reference to a constant '1'.
Gramatical errors aside, see if this code makes anything clearer.
#!/usr/local/bin/perl
($_ = 'of Perl Wisdom') =~ s/(.*)/Just Another Perl \1, /;
print if /(\S+ )+of \1/;
($_ = 'Hacker') =~ s/(.*)/Just Another Perl \1, /;
print if /(\S+ )+$1/;
print "and Just another Perl ",\1;
Note that in this case you could use $1 rather than \1 in the first and third lines but not in the second. And that you cannot use \1 instead of $1 in the fourth.
An interesting? variaton.
By removing the negation and printing out what matched (this time using $1) you can get the
largest factor of a number. (or that many x's anyway) )
perl -e 'while($l++<99){$_.=x;print $l,$1,$/if/^x$|^(xx+)\1+$/}'
Or a half a christmas tree. :)
In reply to \1 Greed, $1
by kryten
in thread Primes
by Mo
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.