Perl Dollar Issue

I get a bunch of text from an external source, storing it in a variable, and then display this variable as part of a larger block of HTML. I need to display it as it is, and the dollar signs give me problems.

Here's the setting:

# 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 included in it.

I tried to avoid the dollar sign using s/\$/\$/g , because I understand that the first \$ does the re-expression, so it searches for $ , and the second \$ is what is inserted and then exits Perl, so that it just displays $ . But I can’t make it work.

Here is what I get:

 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 is 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 leads me to this question . When I try to use an array and for a loop in the response, it has no effect.

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

+4
source share
3 answers

When you create a double-quoted string, the change of variables occurs immediately. In this case, your string will never contain the $ character. If you want $ appear in the string, use single quotes or avoid it, and keep in mind that you will not get a variable replacement if you do.

As for your regular expression, this is odd. He searches for $ and replaces them with $ . If you want a backslash, you need to hide them too.

+7
source

And here is 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 perhaps the following will do:

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

Or would you like 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. 
+4
source

Your mistake is to use double quotes instead of single quotes in your variable declaration.

It should be:

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

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

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

+2
source

Source: https://habr.com/ru/post/1444672/


All Articles