perl-diddler has asked for the wisdom of the Perl Monks concerning the following question:
I especially liked methods 2 & 3 as they didn't need interpolation, with 3 being better as it didn't require an intermediate variable.sub iregex { qr/ ... /ix } 1) my $regex = iregex() if ($isbn =~ m/$regex/ ) { print "Matched!\n } 2) my $regex = iregex() if ($isbn =~ $regex ) { print "Matched!\n } 3) if ($isbn =~ iregex() ) { print "Matched!\n }
Seeing that I wanted to try out capturing all matching sub expressions using 'g' added to my 'qr' expression, but I'm getting a deprecation error:
> perl -we'use strict;use P; my $re = qr{ (\w+) }gx; my $dat = "Just another cats meow"; my @matches = $dat =~ $re; P "#matches=%s, matches=%s", scalar(@matches), \@matches; exit scalar(@matches);' output: Having no space between pattern and following word is deprecated at -e + line 2. Bareword found where operator expected at -e line 2, near "qr/ (\w+) / +gx" syntax error at -e line 2, near "qr{ (\w+) }gx" Execution of -e aborted due to compilation errors.
If I move the 'g' option down to where the RE is used and use a *second* "RE" operator (i.e.: /.../g) and interpolate my expression into another RE (the slowest of the above 3 options), I get:
> perl -we'use strict;use P; my $re = qr{ (\w+) }x; my $dat = "Just another cats meow"; my @matches = $dat =~ /$re/g; P "#matches=%s, matches=%s", scalar(@matches), \@matches; exit scalar(@matches);' output: #matches=4, matches=["Just", "another", "cats", "meow"]
So why can't I add the global switch to the "qr" expression? FWIW, I also tried qr{ (?xg) }. Perl strips out the 'g' and tells me to add it to the end of the RE -- where it is deprecated:
perl -we'use strict;use P; my $re = qr{ (?xg) (\w+) }; my $dat = "Just another cats meow"; my @matches = $dat =~ $re; P "#matches=%s, matches=%s", scalar(@matches), \@matches; exit scalar(@matches);' output: Useless (?g) - use /g modifier in regex; marked by <-- HERE in m/ (?xg + <-- HERE ) (\w+) / at -e line 2. #matches=1, matches=["another"]
So how can I attach the "/g" modifier to my "qr" regex so I can use the direct match as in #2 or #3 above?
Thanks...P.S. - I also just noticed that in addition to stripping out the 'g' option, the 'x' option doesn't seem to work in the regex's parens, i.e. - (?x).