4

I have a simple line of Perl

s/$var/'string'/g

The issue is that $var contains a string like jkdlsf$lkjl. Note the dollar sign in the middle. It seems because of this dollar sign the replace is not working. How do I escape this when it is inside a variable?

choroba
  • 231,213
  • 25
  • 204
  • 289
evolution
  • 4,332
  • 5
  • 29
  • 34

3 Answers3

10

Use the \Q quote:

s/\Q$var/'string'/g
choroba
  • 231,213
  • 25
  • 204
  • 289
  • Exactly. ) Here's quite [a helpful article](http://www.effectiveperlprogramming.com/blog/1496) about it. – raina77ow May 28 '13 at 17:03
  • @raina77ow pity the link is broken. I came here by searching for the meaning of `\Q`. Any other explanation available? – fedorqui Jan 06 '15 at 10:22
  • 1
    That "helpful article" is [Understand the order of operations in double quoted contexts](http://www.effectiveperlprogramming.com/2012/01/understand-the-order-of-operations-in-double-quoted-contexts/) – brian d foy Sep 28 '15 at 15:29
5

Use quotemeta or the \Q and \E embedded regex constructs:

s/\Q$var\E/'string'/g;

# or

my $var = quotemeta 'jkdlsf$lkjl';
s/$var/'string'/g;
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
0

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

Sysyphus
  • 1,061
  • 5
  • 10
  • 1
    does not answer my question. – evolution May 28 '13 at 17:00
  • @evolution Your question was "How do I escape this when it is inside in a stored variable?" and the above answer tells you exactly that. – Vedran Šego May 28 '13 at 17:02
  • Use `\Q...\E` if you want nothing in $var to be interpreted. Use the above method if you want just `$`s to be escaped, but other characters to keep their special status. If you're after something else then I'm afraid I don't know what you're asking. – Sysyphus May 28 '13 at 17:06
  • This solution will also modify the contents of `$var`, a side effect that is not necessarily acceptable depending on the situation. – Lorkenpeist May 28 '13 at 17:51