jffry has asked for the wisdom of the Perl Monks concerning the following question:
In another thread of mine someone responded with a snippet that I've been trying to wrap my head around ever since. This subject is a major tangent from the other thread, so I think it should be on its own. I hope that's OK.
Here is the original snippet. It is the contents of the s// regexp operator that has me completely stumped.
%d = ( foo => sub { "[@_]"; }, bar => sub { "(@_)"; }, ); $_ = 'foo fooz bar baz1'; s/(\w+)(?(?{ !$d{$1} })(?!))/$d{$1}->($1)/ge; print "$_\n";
Here is the output.
[foo] [foo]z (bar) baz1
I added comments to the code in my attempt to understand what was happening. Most of my explanatory text is contained therein.
s/ (\w+) # One or more word chars in capture buffer 1. Got it. ( # Embedding a regexp modification character or what? # So everything within this set of parenthesis is # supposed to evaluate to either m, s, i, x, p, g, or c? # I don't get it. # Also, why is all this on the left side of s\\? Why are we # _matching_ this? ?(?{ !$d{$1} }) # This is really just used as a boolean to # indicate that a hash key exists. I get it, # kind of. (?!) # From perldoc, "a zero-width negative look-ahead # assertion. I might understand this if only there was # a pattern after the "?!". ) /$d{$1}->($1)/gex; print "$_\n"; # Here is my walkthrough for 'foo'. # 1. (\w+) matches 'foo'. # 2. $d{$1} is _true_. !_true_ = false. In this case, false is "1". # 3. (?!) says to *not* match a "1" followed by null. Maybe? # 4. (?...) means use the 1 not followed by null as a regexp modifier # to 'foo'? What?!
A few of my big failures to comprehend I think are:
Thanks.
EDIT: I updated the $_ var to include the "baz1" string.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regular expression operators (?{code}), (?!pattern), and (?...)
by Khen1950fx (Canon) on Oct 31, 2009 at 01:07 UTC | |
|
Re: Regular expression operators (?{code}), (?!pattern), and (?...)
by ikegami (Patriarch) on Oct 31, 2009 at 02:06 UTC | |
|
Re: Regular expression operators (?{code}), (?!pattern), and (?...)
by AnomalousMonk (Archbishop) on Oct 31, 2009 at 01:49 UTC |