Passing a regex substitution as a variable in Perl?

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

    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.

提交回复
热议问题