Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble escaping dollar sign in Perl

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?

like image 671
Steve Blackwell Avatar asked Dec 11 '22 20:12

Steve Blackwell


2 Answers

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.

like image 165
paddy Avatar answered Jan 03 '23 13:01

paddy


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.
like image 33
ikegami Avatar answered Jan 03 '23 13:01

ikegami