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.

In reply to Re: Bizarreness in ?PATTERN? and g by Anonymous Monk
in thread Bizarreness in ?PATTERN? and g by BUU

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.