[Omaha.pm] Fwd: weird perl bug

Jay Hannah jhannah at mutationgrid.com
Fri Nov 19 08:40:42 PST 2010


On Nov 18, 2010, at 10:20 PM, Dan Linder wrote:
> The "/g" flag carries across multiple matching calls/lines?
> 
> Learn something new every day...  Thanks!

Ya, Andy's explanation helped me too. At a glance I had no idea what was going on.  :)

In array context all the /g matches are slurped out "in one line of code:"

   my (@words) = ( $string =~ /(\w+)/g );

And nothing "weird" happens. But in scalar context perl "remembers" so that functions like pos() can do their thing. I used pos() frequently in bioinformatics work (genetic sequence searches):

   $ cat j.pl
   my $string = "foo bar baz boogity baggity";
   while ($string =~ /(\w+)/g) {
      printf("%s match ended at position %s\n", $1, pos($string));
      # and do whatever else you want. perl remembers where you were
      # in the $string =~ match above!
   }

   $ perl j.pl  
   foo match ended at position 3
   bar match ended at position 7
   baz match ended at position 11
   boogity match ended at position 19
   baggity match ended at position 27

:)

Jay Hannah
Software Architect
jhannah at mutationgrid.com | http://mutationgrid.com | 1-402-598-7782







More information about the Omaha-pm mailing list