While the method using eval
to compile a new substitution is probably the most straightforward, you can create a substitution that is more modular:
use warnings;
use strict;
sub subst {
my ($search, $replace, $mod) = @_;
if (my $eval = $mod =~ s/e//g) {
$replace = qq{'$replace'};
$replace = "eval($replace)" for 1 .. $eval;
} else {
$replace = qq{"$replace"};
}
sub {s/(?$mod)$search/$replace/ee}
}
my $sub = subst '(abc)', 'uc $1', 'ise';
local $_ = "my Abc string";
$sub->();
print "$_
"; # prints "my ABC string"
This is only lightly tested, and it is left as an exercise for the reader to implement other flags like g
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…