naikonta has asked for the wisdom of the Perl Monks concerning the following question:
I write a compiled regex as following,
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 = '(' . join('|', @patterns) . ')'; $pat = qr/$pat/i;
But I got a syntax error near "$pat = qr/$pat/gi", so I move the 'g' on the substitution construct.$pat = qr/$pat/gi; s/$pat/something/;
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,$pat = qr/$pat/i; s/$pat/something/g;
It went OK, and this is not supprising me since I use this kind of construct many times before:perl -e 'print if /perl/gi'
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?$str = 'nothing but perl can parse Perl'; @match = $str =~ /(perl)/gi; print for @match;
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: The 'g' modifier in compiled regex
by ikegami (Patriarch) on Apr 09, 2007 at 05:27 UTC | |
by naikonta (Curate) on Apr 09, 2007 at 08:16 UTC | |
by rodion (Chaplain) on Apr 09, 2007 at 09:28 UTC | |
by exussum0 (Vicar) on Apr 09, 2007 at 15:01 UTC | |
by demerphq (Chancellor) on Apr 09, 2007 at 16:56 UTC | |
Re: The 'g' modifier in compiled regex
by japhy (Canon) on Apr 09, 2007 at 03:24 UTC | |
by bart (Canon) on Apr 09, 2007 at 09:23 UTC |
Back to
Seekers of Perl Wisdom