my $test = "There was once an\n ugly ducking";
if ($test =~ m/ugly/g) {
if ($test =~ m/here/g) {
print 'Match';
}
}
Results in no output, but
my $test = "There was once an\n ugly ducking";
if ($test =~ m/here/g) {
if ($test =~ m/ugly/g) {
print 'Match';
}
}
results in Match!
If I remove the g flag from the regex, then the second internal test matches whichever way around the matches appear in $test. I can't find a reference to why this is so.
Yes. That behaviour is documented in perlop man page. Using m/.../ with g flag advances in the string for the next match.
In scalar context, each execution of "m//g" finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the "pos()" function; see "pos" in perlfunc. A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the "/c" modifier (e.g. "m//gc"). Modifying the target string also resets the search position.
So, in first case after ugly there isn't any here substring, but in second case it first matches here in There and later it finds the ugly word.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With