如何在 Perl 替换运算符的替换端使用变量? [英] How can I use a variable in the replacement side of the Perl substitution operator?
问题描述
我想执行以下操作:
$find = "start (.*) end";
$replace = "foo \1 bar";
$var = "start middle end";
$var =~ s/$find/$replace/;
我希望 $var 包含foo middle bar",但它不起作用.也没有:
I would expect $var to contain "foo middle bar", but it does not work. Neither does:
$replace = 'foo \1 bar';
不知何故,我错过了有关转义的内容.
Somehow I am missing something regarding the escaping.
推荐答案
在替换方面,你必须使用 $1,而不是 \1.
On the replacement side, you must use $1, not \1.
而且你只能通过替换一个给出你想要的结果的可评估表达式来做你想做的事情,并告诉 s///使用/ee 修饰符来评估它,如下所示:
And you can only do what you want by making replace an evalable expression that gives the result you want and telling s/// to eval it with the /ee modifier like so:
$find="start (.*) end";
$replace='"foo $1 bar"';
$var = "start middle end";
$var =~ s/$find/$replace/ee;
print "var: $var\n";
要了解为什么需要 "" 和双/e,请在此处查看双 eval 的效果:
To see why the "" and double /e are needed, see the effect of the double eval here:
$ perl
$foo = "middle";
$replace='"foo $foo bar"';
print eval('$replace'), "\n";
print eval(eval('$replace')), "\n";
__END__
"foo $foo bar"
foo middle bar
(尽管池上指出,单个/e 或双 e 的第一个/e 并不是真正的 eval()
;相反,它告诉编译器替换是代码compile,而不是一个字符串.尽管如此,eval(eval(...))
仍然展示了为什么你需要做你需要做的事情才能让/ee 按预期工作.)
(Though as ikegami notes, a single /e or the first /e of a double e isn't really an eval()
; rather, it tells the compiler that the substitution is code to compile, not a string. Nonetheless, eval(eval(...))
still demonstrates why you need to do what you need to do to get /ee to work as desired.)
这篇关于如何在 Perl 替换运算符的替换端使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!