Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://626295]
help
Chatterbox?
[Corion]: I found Android Studio quite nice as a Java IDE, but then, I didn't try anything serious with it
[chacham]: it is a nice ide. its just that upgrading it always causes issues with mismatched versions of whatever
[Corion]: chacham: Oh, yes, reinstalling all the SDK versions and Gradle and whatnot, yes, even in the short time I used it (2 weeks?) I felt that pain

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2017-03-29 07:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (344 votes). Check out past polls.