I need to pass a regex substitution as a variable:
sub proc {
my $pattern = shift;
my $txt = \"foo baz\";
$txt =~ $pattern;
}
my $pattern = \'s
eval "$txt =~ $pattern";This becomes
eval "\"foo baz\" =~ s/foo/bar/"and substitutions don't work on literal strings.
This would work:
eval "\$txt =~ $pattern"but that's not very pleasing. eval is almost never the right solution.
zigdon's solution can do anything, and Jonathan's solution is quite suitable if the replacement string is static. If you want something more structured than the first and more flexible than the second, I'd suggest a hybrid:
sub proc {
my $pattern = shift;
my $code = shift;
my $txt = "foo baz";
$txt =~ s/$pattern/$code->()/e;
print "$txt\n";
}
my $pattern = qr/foo/;
proc($pattern, sub { "bar" }); # ==> bar baz
proc($pattern, sub { "\U$&" }); # ==> FOO baz