On 9 Oct 2003, at 19:38, Jonathan Eisler (via RT) wrote: > I think this is a bug, but it may just be strange behaviour: global > matching (ie: m/.../g ) behaves differently when the extracted results > are > saved to lexical variables or when the $1, $2, etc, implicit variables > are > used. > > Consider: > > my $text = "Foo\nBar\n"; > while ( $text =~ /(\w+)/g ) { print $1, "\n" } > > The above script prints 2 lines to standard out, as expected: > "Foo\nBar\n". Yes, thats because in a scalar context m//g will remember where it left off and the next match will start where the previous left off. > Now consider: > > my $text = "Foo\nBar\n"; > while ( my ( $name ) = ( $text =~ /(\w+)/g ) ) { print $name, "\n" } > > The above script goes into an infinite loop, printing "Foo\n" to stdout > over and over. Correct. the () puts the m//g into a list context. In a list context m//g will return all matches as a list. As you only have one variable in the my() you only see the first match. Each time m//g is called in a list context it restarts from the start of the string. > Shouldn't the two scripts behave equivalently? No. Graham. > > Note, I've tested this on: > perl 5.00503 for freebsd > perl 5.8.1 for linux > perl 5.8.0 for darwin > I get the same behaviour on all 3. >Thread Previous | Thread Next