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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.