Hi all. japhy speaking. Here's the run-down:
- The regex variables are not reset or changed after a failed regex.
- The /g modifier, in scalar context, tells the regex to match once,
and then update pos($str) to wherever the regex ended in the string. The
next time that string is matched against by a regex with the /g flag, the
regex will start looking NO SOONER than pos($str) in the string. pos()
is not tied to a regex, it's tied to a string.
- A m?? regex matches only once (in between calls to reset()). That
behavior is tied to THAT specific regex.
- Perl is compiled. That means /x/ for 1, 2; is different
from /x/; /x/;.
Put it all together and you have this fact:
# code 1
$str = "abc";
for (1, 2, 3) {
print $1 if $str =~ ?(.)?g;
}
# code 2
$str = "abc";
print $1 if $str =~ ?(.)?g;
print $1 if $str =~ ?(.)?g;
print $1 if $str =~ ?(.)?g;
The first code only prints 'a'. The second code prints 'abc'. This is
because the first code has only one PMOP (Perl's internal representation of
a pattern match operation), whereas the second code has THREE of them. Each
PMOP has its own flags, such as the "I'm a m?? regex" flag.
Now for a bit of fun. What does this code print?
$str = "abc";
for (1, 2, 3) {
$str =~ ?(.)?g;
print $1;
}
Does it print "a" (and then two empty strings)? No. Why not? Because the
regex variables ($1, et. al.) are in a *slightly* larger scope than you'd
expect: they retain their values for the duration of that for loop. It would
be similar to saying:
$str = "abc";
{
local ($_1, $_2, ...);
for (1, 2, 3) {
$str =~ ?(.)?g and ($_1, $_2, ...) = ($1, $2, ...);
print $_1;
}
}
except, of course, that you don't have to.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.