Passing a regex substitution as a variable in Perl?

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

    I need to pass a regex substitution as a variable

    Do you? Why not pass a code reference? Example:

    sub modify
    {
      my($text, $code) = @_;
      $code->($text);
      return $text;
    }
    
    my $new_text = modify('foo baz', sub { $_[0] =~ s/foo/bar/ });
    

    In general, when you want to pass "something that does something" to a subroutine ("a regex substitution" in the case of your question) the answer is to pass a reference to a piece of code. Higher Order Perl is a good book on the topic.

提交回复
热议问题