Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Regex code block executes twice per match using look-arounds

by ikegami (Pope)
on Jul 12, 2007 at 18:21 UTC ( #626295=note: print w/ replies, xml ) Need Help??


in reply to Regex code block executes twice per match using look-arounds

The code block also executes twice if I am just matching using look-arounds rather than substituting. ... Can any Monk throw some light on what is happening here?

There's one more check after your (?{ print ... }).

Right before declaring a match, Perl does an extra check when g is used. Perl checks if the starting position of the match (pos) and the length of the match is the same as the last loop through the regexp. If it is, the match is nulified, pos is incremented, and another match is attempted.

Consider, the following two snippets.

while ('abc' =~ /(.)/g) { print($1); }
while ('abc' =~ /(?=(.))/g) { print($1); }

In the first snippet, the regexp matches a character every pass, so pos is always incremented by one (the length of the match) every pass.

In the second snippet, the regexp matches zero characters every pass (since (?=...) always matches zero characters when it matches), so pos is incremented by zero (the length of the match) every pass.

Therefore, without the afformentioned check, pos will never advance beyond zero in the second snippet, printing an infinite stream of as. With the check, Perl realizes it matched pos=0 len=0 twice and takes action to correct that.

You can see that effect by running the following snippet.

$_ = 'abc'; while (/ ( (?=.) ) (?{ printf("pos=%d len=%d\n", pos($_), length($1)); }) /xg) { print("Match\n"); } print("\n"); while (/ ( . ) (?{ printf("pos=%d len=%d\n", pos($_), length($1)); }) /xg) { print("Match\n"); }
pos=0 len=0 Match pos=0 len=0 # Same pos & len as last pass -> No match. pos=1 len=0 Match pos=1 len=0 # Same pos & len as last pass -> No match. pos=2 len=0 Match pos=2 len=0 # Same pos & len as last pass -> No match. pos=1 len=1 Match pos=2 len=1 Match pos=3 len=1 Match


Comment on Re: Regex code block executes twice per match using look-arounds
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2014-08-23 03:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (171 votes), past polls