Escape the dollar sign inside a variable

I have a simple Perl line

s/$var/'string'/g 

The problem is that $ var contains a string like jkdlsf$lkjl . Pay attention to the dollar sign in the middle. It seems that because of this dollar sign, the replacement does not work. How to avoid this when it is inside a variable?

+4
source share
3 answers

Use \Q quote:

 s/\Q$var/'string'/g 
+10
source

Use quotemeta or the regex \Q and \E built-in constructors:

 s/\Q$var\E/'string'/g; # or my $var = quotemeta 'jkdlsf$lkjl'; s/$var/'string'/g; 
+5
source

You can avoid them with backslashes: $var=~s/\$/\\\$/g

0
source

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


All Articles