perl

Why can't I embed a g modifier within a regex pattern?


my $modifiers = 'i';
my $string = "abcabc\n";
$string =~ s/(?$modifiers)B/Z/;
print $string;
$modifiers = 'g';
$string =~ s/(?$modifiers)a/q/;
print $string;

The first regex works and changes the first b to Z.

The second regex gives:

Useless (?g) - use /g modifier in regex; marked by <-- HERE in m/(?g <-- HERE

Why is the error message saying it's in m/ when it is in s/?

I don't know if the /g is going to be needed in advance. Is the only way to deal with this to remove the g from $modifiers and use an if statement to choose one of almost two identical regex statements, one having a /g?


Solution

  • As seen in Extended Patterns, the allowed modifiers are:

    (?adlupimnsx)
    

    Although g is a modifier, it can not be used as an extended pattern the way you are trying to use it.