in reply to Bizarreness in ?PATTERN? and g

Hi all. japhy speaking. Here's the run-down: 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.