in reply to strange behavior of grep with global match [resolved]

The problem is that /.../g stores the match position in pos($_), but it is not reset anywhere (because without the /g the regex engine doesn't touch pos at all, iirc). Since $_ is just an alias to a particular array element, each element has its own pow().

If you add a print pos($strings[1]), "\n" in the loop (after the grep, in your first example) you'll see that it first prints 10, in the second iteration it's undef, then 10 again, then undef again.

So to summarize, a /.../g attaches state to a string, and confuses you if it's not reset. In the most common cases such as while (/foo/g) { ... } you always exhaust the matches until there is a failed match, resetting pos at the end and not causing confusion.

In Perl 6 this is avoided by storing the match position inside the match object, not associated with the string

Replies are listed 'Best First'.
Re^2: strange behavior of grep with global match
by ig (Vicar) on Aug 07, 2009 at 09:35 UTC

    That reminds me of things I knew, vaguely, and ties them together into an explanation I understand. Enlightenment attained!! Eureka!! Thanks moritz.