I need to pass a regex substitution as a variable:
sub proc {
my $pattern = shift;
my $txt = \"foo baz\";
$txt =~ $pattern;
}
my $pattern = \'s
I found a probably better way to do it:
sub proc {
my ($pattern, $replacement) = @_;
my $txt = "foo baz";
$txt =~ s/$pattern/$replacement/g; # This substitution is global.
}
my $pattern = qr/foo/; # qr means the regex is pre-compiled.
my $replacement = 'bar';
proc($pattern, $replacement);
If the flags of the substitution have to be variable, you can use this:
sub proc {
my ($pattern, $replacement, $flags) = @_;
my $txt = "foo baz";
eval('$txt =~ s/$pattern/$replacement/' . $flags);
}
proc(qr/foo/, 'bar', 'g');
Please note that you don't need to escape / in the replacement string.