开发者

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:

foo

After running the fo开发者_开发百科llowing command (in bash):

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

the output is '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'.

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?

Also, I tried changing the second one to s///e, to no effect.

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):

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

The ee evals the replacement part as a text string. See 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).


/ee by @maxelost is correct.

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

so I'm guessing this works in bash:

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

in windows:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜