regexmegex has asked for the wisdom of the Perl Monks concerning the following question:

Hello everyone, I have a problem that stumps me. Better illustrated by the code snippet:
my $ref->{number} = 123; my $arg = shift ( @ARGV ) ; my $regex = qr/(one|two|three|four)/; for (1..10) { if ( ref $ref eq 'HASH' and $arg =~ /$regex/ig ) { print "$arg matches\n"; } else { print "$arg doesn't match\n"; } }
Executed we get:
C:\src>perl monks.pl one one matches one doesn't match one matches one doesn't match one matches one doesn't match one matches one doesn't match one matches one doesn't match
The perl version and OS doesn't matter, it displays the same behavior in Linux & Windows. Perl 5.8 and Perl 5.12. Any ideas will be appreciated.

Replies are listed 'Best First'.
Re: Regex matches the same pattern alternatively
by AnomalousMonk (Archbishop) on Oct 23, 2011 at 07:37 UTC

    Further to ikegami's point, here's an illustration of the way the /g modifier causes the regex engine to interact with the position offset (if that's the right term) of a string as returned by pos.

    >perl -wMstrict -le "my $s = 'oneone'; my $regex = qr/one/; ;; for (1 .. 6) { if ($s =~ /$regex/g) { printf qq{matches '$&' at %d, pos at %d \n}, $-[0], pos $s; } else { print 'no match'; } } " matches 'one' at 0, pos at 3 matches 'one' at 3, pos at 6 no match matches 'one' at 0, pos at 3 matches 'one' at 3, pos at 6 no match
      Thanks AnomalousMonk. This helps.
Re: Regex matches the same pattern alternatively
by ikegami (Patriarch) on Oct 23, 2011 at 06:52 UTC
    It's due to your misuse of /g. Get rid of the /g.
      Thank you ikegami! I have a lot to learn.