Passing a regex substitution as a variable in Perl?

后端 未结 9 1957
青春惊慌失措
青春惊慌失措 2020-12-13 06:45

I need to pass a regex substitution as a variable:

sub proc {
    my $pattern = shift;
    my $txt = \"foo baz\";

    $txt =~ $pattern;
}

my $pattern = \'s         


        
9条回答
  •  长情又很酷
    2020-12-13 07:34

    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

提交回复
热议问题