Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behaviour of the global g regex flag [duplicate]

Tags:

regex

global

perl

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.

like image 610
Santrix Avatar asked Jan 06 '14 10:01

Santrix


1 Answers

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.

like image 129
Birei Avatar answered Oct 21 '22 14:10

Birei