http://qs1969.pair.com?node_id=608925

naikonta has asked for the wisdom of the Perl Monks concerning the following question:

I write a compiled regex as following,
$pat = '(' . join('|', @patterns) . ')'; $pat = qr/$pat/i;
I then later add the 'g' modifier as this regex will be used in substituion that is expected to substitute all occurences, as in
$pat = qr/$pat/gi; s/$pat/something/;
But I got a syntax error near "$pat = qr/$pat/gi", so I move the 'g' on the substitution construct.
$pat = qr/$pat/i; s/$pat/something/g;
which is just fine. I wonder if this might be because 'g' is the property of a substitution, not a pattern match. I looked at the perlop and I did see the entry "qr/STRING/imosx", there's no 'g' there. However, this doesn't fit to my current undertanding about the 'g' usage, so I tried the ordinary matching construct,
perl -e 'print if /perl/gi'
It went OK, and this is not supprising me since I use this kind of construct many times before:
$str = 'nothing but perl can parse Perl'; @match = $str =~ /(perl)/gi; print for @match;
I'm aware that qr// is only compilation and m// is compilation and execution at once. But, why 'g' doesn't work in qr//? Does it have anything to do with the way the regex is precompiled?

I thought that when perl precompiled a qr/regex/g, it noticed the g and planned (if this term is correct) to do the multimatching whenever the regex is later used, either in normal matching or substitution. I might overlook any explanation in the perlop and perlre and perlfaq6, or anywhere else about this, so where can I find it? I expected something in the perlop that says something like "you can't use g here because bla bla ....".

What I need is I compile a multimatch regex once and I use it in many substitution constructs without ever worrying about the 'g' modifier anymore.