Could you perhaps explain why?
In conjunction with the SO explanations linked by rminner, consider this variation on rminner's code. The @- special match array variable (see perlvar) is used to show the starting position of the match that is found: $-[0]
Then pos is printed to show the string position from which further matching will continue. The second match never finds 'foo' because when it trys to do so, it's already past it! Now remove all the /g regex modifiers from all the matches and see what happens. See perlre, perlretut.
>perl -wMstrict -le
"my $string = 'foo bart bare';
;;
if ($string =~ m{bar}g) { print qq{found bar at offset $-[0]}; }
print 'string pos is ', defined(pos $string) ? pos $string : 'UNDEF';
;;
if ($string =~ m{foo}g) { print qq{found foo at offset $-[0]}; }
print 'string pos is ', defined(pos $string) ? pos $string : 'UNDEF';
;;
if ($string =~ m{bar}g) { print qq{found bar at offset $-[0]}; }
print 'string pos is ', defined(pos $string) ? pos $string : 'UNDEF';
"
found bar at offset 4
string pos is 7
string pos is UNDEF
found bar at offset 4
string pos is 7
In the code as shown, the second 'bar' match at offset 9 is never found because the intervening m{foo}g match fails and 'resets' the string match position. With all /g modifiers in place, try matching with m{foo}gc (note the added /c modifier) and see what happens.
|