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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.