简体   繁体   English

如何绕过Perl的字符串转义s ///中的替换字符串?

[英]How to Circumvent Perl's string escaping the replacement string in s///?

I'm not sure what exactly to call this, but I've been able to reproduce my problem with two one-liners. 我不确定究竟是什么称呼它,但我已经能够用两个单行重现我的问题。

Starting from a file 'test.txt' containing the following: 从包含以下内容的文件'test.txt'开始:

foo

After running the following command (in bash): 运行以下命令后(在bash中):

perl -n -e "s/(\w)oo/$1ar/; print;" test.txt

the output is ' far ' 输出是' far '

However, when I introduce a variable containing the replacement string, 但是,当我引入一个包含替换字符串的变量时,

perl -n -e '$bar = q($1ar); s/(\w)oo/$bar/; print;' test.txt

the output is ' $1ar '. 输出为' $1ar '。

What do I need to change so that the second program will also output ' far ' and what keywords do I need to learn that would have made this answer Googleable? 我需要更改什么,以便第二个程序也输出' far '以及我需要学习哪些关键字才能使这个答案成为可用的?

Also, I tried changing the second one to s///e, to no effect. 此外,我尝试将第二个更改为s /// e,无效。

Edit: This wasn't really the question I wanted to ask, which is here . 编辑:这不是我想问的问题,就在这里

This works for me (in bash; you may need to change your quotes): 这适用于我(在bash中;您可能需要更改引号):

perl -n -e '$bar = "\${1} . ar"; s/(\w)oo/$bar/ee; print;' test.txt

The ee evals the replacement part as a text string. ee将替换部分视为文本字符串。 See perlop(1) . perlop(1)

I'm hoping someone will come along with something better, but this works for me: 我希望有人会有更好的东西,但这对我有用:

perl -n -e '$bar=q($1."ar"); s/(\w)oo/eval($bar)/e; print;' test.txt

I'm setting $bar to the expression that concatenates $1 to 'ar' so that I can eval it in the replacement portion (using the e flag). 我将$ bar设置为将$1连接到'ar'的表达式,以便我可以在替换部分(使用e标志)中评估它。

/ee by @maxelost is correct. @ eelost的/ ee是正确的。

This works in a perl program 这适用于perl程序
$bar = q("${1}ar");
$str = "foo";
$str =~ s/(\\w)oo/$bar/ee;
print $str;

so I'm guessing this works in bash: 所以我猜这个在bash中起作用:

perl -e '$bar = q("${1}ar"); s/(\\w)oo/$bar/ee; print;' test.txt

in windows: 在Windows中:

perl -e "$bar = q(\\"${1}ar\\"); s/(\\w)oo/$bar/ee; print;" test.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM