Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在制作一个正则表达式构造函数。但是运行时:
my $text = 'a a a'; my $replace = '$1/$2-$3'; $text =~ s/(\w) (\w+) (\w+)/$replace/gmi;
$text here = '$1/$2-$3'; 所以 $1,$2,$3 并没有改变,而是按原样放置在 $replace 中。我将如何使它使用 $replace 内容作为手动打印的 replate 模式?
$replace只是一个字符串。如果您希望将其作为代码进行评估,则需要/e在替换中使用修饰符。但是您还需要为评估准备字符串以插入变量:
$replace
/e
my $replace = 'qq($1/$2-$3)'; $text =~ s/(\w) (\w+) (\w+)/$replace/gmiee;
我们使用双重评估首先将变量转换为字符串,然后评估该字符串。
但是,每当您发现自己依赖 eval 时,您可能正在做一些不必要的事情。正如 OmnipotentEntity 正确指出的那样,Eval 可能相当邪恶,所以使用它时要非常小心。