perlquestion
naikonta
I write a compiled regex as following,
<code>
$pat = '(' . join('|', @patterns) . ')';
$pat = qr/$pat/i;
</code>
I then later add the 'g' modifier as this regex will be used in substituion that is expected to substitute all occurences, as in
<code>
$pat = qr/$pat/gi;
s/$pat/something/;
</code>
But I got a syntax error near "$pat = qr/$pat/gi", so I move the 'g' on the substitution construct.
<code>
$pat = qr/$pat/i;
s/$pat/something/g;
</code>
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,
<code>
perl -e 'print if /perl/gi'
</code>
It went OK, and this is not supprising me since I use this kind of construct many times before:
<code>
$str = 'nothing but perl can parse Perl';
@match = $str =~ /(perl)/gi;
print for @match;
</code>
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?
<p>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 ....".
<p>
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.