Trouble escaping dollar sign in Perl

会有一股神秘感。 提交于 2021-02-05 05:41:11

问题


I'm getting a bunch of text from an outside source, saving it in a variable, and then displaying that variable as part of a larger block of HTML. I need to display it as is, and dollar signs are giving me trouble.

Here's the setup:

# get the incoming text
my $inputText = "This is a $-, as in $100. It is not a 0.";

print <<"OUTPUT";
before-regex: $inputText
OUTPUT

# this regex seems to have no effect
$inputText =~ s/\$/\$/g;

print <<"OUTPUT";
after-regex:  $inputText
OUTPUT

In real life, those print blocks are much larger chunks of HTML with variables inserted directly.

I tried escaping the dollar signs using s/\$/\$/g because my understanding is that the first \$ escapes the regex so it searches for $, and the second \$ is what gets inserted and later escapes the Perl so that it just displays $. But I can't get it to work.

Here's what I'm getting:

before-regex: This is a 0, as in . It is not a 0.
after-regex:  This is a 0, as in . It is not a 0.

And here's what I want to see:

before-regex: This is a 0, as in . It is not a 0.
after-regex:  This is a $-, as in $100. It is not a 0.

Googling brings me to this question. When I try using the array and for loop in the answer, it has no effect.

How can I get the block output to display the variable exactly as it is?


回答1:


When you construct a string with double-quotes, the variable substitution happens immediately. Your string will never contain the $ character in that case. If you want the $ to appear in the string, either use single-quotes or escape it, and be aware that you will not get any variable substitution if you do that.

As for your regex, that is odd. It is looking for $ and replacing them with $. If you want backslashes, you have to escape those too.




回答2:


And here's what I want to see:

before-regex: This is a 0, as in . It is not a 0.
after-regex:  This is a $-, as in $100. It is not a 0.

hum, well, I'm not sure what the general case is, but maybe the following will do:

s/0/\$-/;
s/in \K/\$100/;

Or did you mean to start with

 my $inputText = "This is a \$-, as in \$100. It is not a 0.";
 # Produces the string: This is a $-, as in $100. It is not a 0.

or

 my $inputText = 'This is a $-, as in $100. It is not a 0.';
 # Produces the string: This is a $-, as in $100. It is not a 0.



回答3:


Your mistake is using double quotes instead of single quotes in the declaration of your variable.

This should be :

# get the incoming text
my $inputText = 'This is a $-, as in $100. It is not a 0.';

Learn the difference between ' and " and `. See http://mywiki.wooledge.org/Quotes and http://wiki.bash-hackers.org/syntax/words

This is for shell, but it's the same in Perl.



来源:https://stackoverflow.com/questions/13279138/trouble-escaping-dollar-sign-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!