On 21/10/2011 19:16, Brandon McCaig wrote:

Thanks for the explanation, Rob. :)

use strict;
use warnings;

use v5.010;

my $data = 'aaa bbb ccc';

say $data;

for my $pattern (qw(bbb aaa ccc))
{
     say join ' ', pos($data) // 'undef', $pattern,
             scalar $data =~ /$pattern/g;
}

__END__

Would not have expected that. Neat. :)

It is perhaps counter-intuitive, but m//g in scalar context is a special
tool meant for simple parsing context-sensitive grammars. Take a look at

  perldoc perlop

in the section titled "\G assertion".

Perhaps it seems more obvious that m//g would return a count of the
occurrences of the pattern in the target string, but

  my $target = 'AAA BBB CCC DDD AAA XXX AAA QQQ BBB CCC BBB SSS';
  my $result = $target =~ /AAA/g;
  printf "result <%s>, pos %s\n", $result, pos($target) // 'undef';

yields

  result <1>, pos 3

indicating that the string was found (a pattern match returns 1 for true
and '' for false) and the next m//g will start after three characters.

So no such luck. To find a pattern count you could either force list
context with the idiomatic

  my $count = () = $target =~ /AAA/g;

which corresponds to the built in 'scalar' to force scalar context (but
sadly doesn't work in all situations).

Or write a simple loop

  my $count;
  $count++ foreach $target =~ /AAA/g;

But Perl 5 is a little broken in this respect, so it is probably best to
use m//g only in list context, if at all.

HTH,

Rob




--
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