Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

\1 Greed, $1

by kryten (Scribe)
on Apr 10, 2000 at 14:55 UTC ( #7225=note: print w/replies, xml ) Need Help??


in reply to RE: RE: RE: Primes
in thread Primes

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. :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://7225]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2023-03-27 09:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which type of climate do you prefer to live in?






    Results (63 votes). Check out past polls.

    Notices?