in reply to Bizarreness in ?PATTERN? and g

Buu's code doesn't seem so bizarre - as many people have commented, it kinda makes sense.

But compare this:
$s="a1 a2 a3"; for (1..2) { print $1 if $s =~ ?a(\d+)?g; }
with this:
$s="a1 a2 a3"; print $1 if $s =~ ?a(\d+)?g; print $1 if $s =~ ?a(\d+)?g;
I would expect these to be equivalent ... but no, the first example prints "1" and the second prints "1 2".

The plot thickens!

update 2004-06-04 01:41 - added conditionals so the first snippet prints "1" rather than "1 1".


--
eval pack("H*", "7072696e74207061636b2822482a222c202236613631373036382229");
# japh or forkbomb? You decide!

Replies are listed 'Best First'.
Re^2: Bizarreness in ?PATTERN? and g
by CountZero (Bishop) on Jun 04, 2004 at 05:50 UTC
    Try printing the value of $_ before each regex and you will see that you try to match 1 and 2 in your first example as the for-loop automagically loads $_ with the "loop index".

    As an aside, your first example prints nothing as the regex never matches!

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re^2: Bizarreness in ?PATTERN? and g
by revdiablo (Prior) on Jun 04, 2004 at 05:45 UTC

    So, hmm. It seems ?? only acts differently if it's inside a loop. The perlop docs mention reset, and reset is only really useful for loops, so perhaps ?? is too? Hopefully someone who knows will come clear this up.

      Each occurence of ?? in code will match only once beteen resets. If you have more than one ??, each one can match once.
      japhy took a look at this but I guess he didn't post about it yet. Basically, loops and repeated statements are not interchangeable - they're compiled differently. He suggested running the following two tests, which are quite enlightening:
      perl -MO=Terse -e '/x/; /x/;' perl -MO=Terse -e '/x/ for 1, 2'


      --
      eval pack("H*", "7072696e74207061636b2822482a222c202236613631373036382229");
      # japh or forkbomb? You decide!