Generally speaking, if (/.../g) does not make sense and should be replaced by if (/.../) [1] .
You did not expect the following to match twice:
my $content = "test"; while ($content =~ /test/g) { print(++$i, "\n"); }
So why do you expect the following to match twice:
my $content = "test"; if ($content =~ /test/g) { print(++$i, "\n"); } if ($content =~ /test/g) { print(++$i, "\n"); }
They are the same!
Suppose $content contains testtest .
- The first time
$content =~ /test/g is evaluated in a scalar context, it corresponds to the first test . - The 2nd time
$content =~ /test/g is evaluated in a scalar context, it corresponds to the second test . - For the 3rd time,
$content =~ /test/g is evaluated in a scalar context, it returns false to indicate that there are no more matches.
This also resets the position at which the $content matches will begin. - The 4th time
$content =~ /test/g is evaluated in a scalar context, it corresponds to the first test . - ...
- There are advanced options for using
if (/\G.../gc) , but these are different. if (/.../g) only makes sense if you are if (/.../g) while loop. (for example, while (1) { ...; last if !/.../g; ... } ).
source share