One extra tweak to the prototype would allow you to
add trailing modifiers without requiring the pesky quotes
around them:
sub qre (&;*) {
my $re = shift->();
eval 'qr/$re/'.(shift//'') || die $@
}
my $regex = qre{ join '|', qw/foo bar/ }i;
print "$regex\n";
__END__
or, from Perl 5.20 onwards:
sub qre :prototype(&;*) {
my $re = shift->();
eval 'qr/$re/'.(shift//'') || die $@
}
my $regex = qre{ join '|', qw/foo bar/ }i;
print "$regex\n";
Damian | [reply] [d/l] [select] |
It works only for some of the modifiers:
my $regex = qre{ join '|', qw/foo bar/ }m;
Returns:
Global symbol "$regex" requires explicit package name at ./1.pl line 1
+1.
Execution of ./1.pl aborted due to compilation errors.
Similarly, s yields
Global symbol "$regex" requires explicit package name at ./1.pl line 1
+1.
syntax error at ./1.pl line 14, at EOF
(Might be a runaway multi-line ;; string starting on line 11)
Execution of ./1.pl aborted due to compilation errors.
($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord
}map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
| [reply] [d/l] [select] |
++choroba
You're quite right: not a good tweak when it's not 100% applicable.
Of course, you could still write:
my $regex = qre{ join '|', qw/foo bar/ }m =>;
but that's probably just adding insult to injury.
And, yes, I was indeed caught out by this because I no longer even think about the m or s modifiers.
Especially now that I can add a standard:
use re '/xms';
at the top of every Perl file. ;-)
Damian | [reply] [d/l] [select] |
Hi choroba,
Hm, the * prototype is a really cool idea, too bad about that... here's a less elegant workaround (also incorporates AnomalousMonk's suggestion). As far as I can tell, for single letter modifiers it's only m and s that cause a problem, the others (/ixpodualn) are fine, and multi-letter modifiers are fine as far as they don't clash with any other subs (like main, min, or sum) or operators (like and, although that's not a valid combination of modifiers). With the letters "msixpodualn" you can actually spell a lot of words :-)
use List::Util qw/min sum/;
sub qre (&;*) {
my $re = shift->();
eval 'qr/$re/'.(@_ ? lc shift : '') || die $@
}
say qre{ join '|', qw/foo bar/ }M;
say qre{ join '|', qw/foo bar/ }msx;
say qre{ join '|', qw/foo bar/ }Min;
say qre{ join '|', qw/foo bar/ }Sum;
__END__
(?^m:foo|bar)
(?^msx:foo|bar)
(?^min:foo|bar)
(?^ums:foo|bar)
Regards, -- Hauke D | [reply] [d/l] [select] |
c:\@Work\Perl>perl -wMstrict -le
"sub qre (&;*) {
my $re = shift->();
return eval 'qr/$re/xms' . (@_ ? shift : '') or die $@;
}
;;
my $regex = qre{ join '|', qw/foo bar/ }i;
print $regex;
"
(?msix:foo|bar)
:-))
Give a man a fish: <%-{-{-{-<
| [reply] [d/l] [select] |
| [reply] [d/l] |
| [reply] [d/l] [select] |