On 21/10/2011 16:32, Jim Gibson wrote:
> 
> I ran the provided program and was going to say that the /g modifier is 
> unnecessary. I took it out and noticed that the results differed. I 
> believe the difference is that some of the matched patterns overlap, and 
> whether or not you want to count them all determines if you should use 
> the /g modifier.
>
> I am not sure why the regular expression engine doesn't always
> restart the search for each iteration of the loop, but I think always
> restart the search for each iteration of the loop, but I think that
> is why you get different results depending upon whether the /g 
> modifier is included or not.

It is nothing to do with matched patterns overlapping. As I tried to
describe, it is the designed behaviour of m//g in scalar context to find
just one match, searching from the end of the previous match if it was
successful, or restarting from the beginning of the string if failed.

This behaviour is independent of any surrounding loop construct, and is
tied to the target string that is being searched. The position where a
m//g pattern match will start looking is reflected in the pos($target)
function, which is undef before any m//g match or after a failed match,
otherwise it is set to the value of $+[0] - the offset of the end of the
matched string.

The program below demonstrates this behaviour. Removing the /g modifier
causes the match to always start at the beginning of the target string,
and is equivalent to preceding the m//g match with

  pos($target) = undef;

in every case.

I hope this is clear.

Rob


use strict;
use warnings;

my $target = 'AAA BBB CCC DDD';
 
#                   0123456789012345678
for my $pattern (qw/AAA XXX CCC AAA AAA/) {
  printf "Looking for %s at pos %s - ", $pattern, pos($target) // 'undef';
  print $target =~ /$pattern/g ? "SUCCESS\n" : "FAILURE\n";
}

__END__

**OUTPUT**

Looking for AAA at pos undef - SUCCESS
Looking for XXX at pos 3 - FAILURE
Looking for CCC at pos undef - SUCCESS
Looking for AAA at pos 11 - FAILURE
Looking for AAA at pos undef - SUCCESS

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to