将正则表达式替换作为变量传递给Perl? [英] Passing a regex substitution as a variable in Perl?
问题描述
我需要将正则表达式替换作为变量传递:
I need to pass a regex substitution as a variable:
sub proc {
my $pattern = shift;
my $txt = "foo baz";
$txt =~ $pattern;
}
my $pattern = 's/foo/bar/';
proc($pattern);
这当然是行不通的.我尝试评估替换:
This, of course, doesn't work. I tried eval'ing the substitution:
eval("$txt =~ $pattern;");
但是那也不起作用.我在这里想念的是什么可怕的东西?
but that didn't work either. What horribly obvious thing am I missing here?
推荐答案
我需要将正则表达式替换作为变量传递
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/ });
通常,当您要将某事做某事"传递给子例程(对于您的问题,是正则表达式替换"),答案是传递对一段代码的引用. 高级Perl 是一本关于该主题的好书.
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.
这篇关于将正则表达式替换作为变量传递给Perl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!