简体   繁体   中英

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 following 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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