如何在Perl替换运算符的替换端使用变量? [英] How to 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.
我修复了丢失的's'
推荐答案
在替换方面,您必须使用$ 1,而不是\ 1.
On the replacement side, you must use $1, not \1.
并且您只能通过替换一个给出您想要的结果的evalable表达式并使用/ee修饰符告诉s///来对其进行评估,来做您想做的事情,如下所示:
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";
要了解为什么需要使用"和double/e,请在此处查看double 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()
;而是,它告诉编译器该替换是要编译的代码,而不是字符串.尽管如此. ,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屋!