in reply to Match a chunk

What are you trying to accomplish with the /g modifier? You are not using it in a very conventional way.

When you use the /g modifier, you update a position within the string from which the next match attempt begins. This position is available by calling pos() on the string:

my $t = "cat hat bat mat"; print pos($t), "\n"; # -> (empty) $t =~ m/at/g; print pos($t), "\n"; # -> 3 $t =~ m/at/g; print pos($t), "\n"; # -> 7 $t =~ m/at/g; print pos($t), "\n"; # -> 11 $t =~ m/hat/g; print pos($t), "\n"; # -> (empty) $t =~ m/at/g; print pos($t), "\n"; # -> 3
For the first three matches you see pos() advancing along the string. The match m/hat/g fails because pos() is already past hat. This failure also causes the next match to start at the beginning of the string.