[Omaha.pm] Fwd: weird perl bug

Andy Lester andy at petdance.com
Thu Nov 18 13:29:00 PST 2010


On Nov 18, 2010, at 3:09 PM, Jay Hannah wrote:

> print "WELCOME\n" if ( ${nc} =~ /$tmp_two_name/g );
> print "TO\n"      if ( ${tc} =~ /$tmp_one_name/g );
> 
> print "BIZZARO\n" if ( ${nc} =~ /$tmp_one_name/g );
> print "LAND\n"    if ( ${nc} =~ /$tmp_two_name/g );

This is not a bug in Perl.

Boil this down to two statements:

print "WELCOME\n" if ( ${nc} =~ /$tmp_two_name/g );
print "BIZZARO\n" if ( ${nc} =~ /$tmp_one_name/g );

The first statement matches, and leaves the internal matching pointer pointing after the first match, which means at the end of the first string.  Then, the second match tries to pick up at the same place, because of the /g flag.

Unless you're trying to do some deep magic here that's not obvious to me, you should NOT be using the /g flag.  The /g flag is only used for matching multiple times the same pattern through the same string, as in

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

xoxo,
Andy

--
Andy Lester => andy at petdance.com => www.techworklove.com => AIM:petdance







More information about the Omaha-pm mailing list