Passing a regex substitution as a variable in Perl?

后端 未结 9 1932
青春惊慌失措
青春惊慌失措 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:26

    s/// is not a regex. Thus, you can't pass it as a regex.

    I don't like eval for this, it's very fragile, with a lot of bordercases.

    I think it's best to take an approach similar to the one Javascript takes: pass both a regex (in Perl, that is qr//) and a code reference for the substitution. For example, to pass parameters to get the same effect as

    s/(\w+)/\u\L$1/g;
    

    You can call

    replace($string, qr/(\w+)/, sub { "\u\L$1" }, 'g');
    

    Note that the 'g' modifier is not actually a flag for the regex (I think attaching it to the regex is a design mistake in Javascript), so I chose to pass it in a 3rd parameter.

    Once the API has been decided on, implementation can be done next:

    sub replace {
        my($string, $find, $replace, $global) = @_;
        unless($global) {
            $string =~ s($find){ $replace->() }e;
        } else {
            $string =~ s($find){ $replace->() }ge;
        }
        return $string;
    }
    

    Let's try it:

    print replace('content-TYPE', qr/(\w+)/, sub { "\u\L$1" }, 'g');
    

    Result:

    Content-Type

    That looks good to me.

提交回复
热议问题