SigmaPiEpsilon
SigmaPiEpsilon

Reputation: 698

Perl regex directly escaping special characters

A perl beginner here. I have been working on some simple one-liners to find and replace text in a file. I read about escaping all special characters with \Q\E or quotemeta() but found this only works when interpolating a variable. For example when I try to replace the part containing special characters directly, it fails. But when I store it in a scalar first it works. Of course, if I escape all the special character in backslashes it also works.

$ echo 'One$~^Three' | perl -pe 's/\Q$~^\E/Two/'
One$~^Three
$ echo 'One$~^Three' | perl -pe '$Sub=q($~^); s/\Q$Sub\E/Two/'
OneTwoThree
$ echo 'One$~^Three' | perl -pe 's/\$\~\^/Two/'
OneTwoThree

Can anyone explain this behavior and also show if any alternative exists that can directly quote special characters without using backslashes?

Upvotes: 0

Views: 202

Answers (1)

ikegami
ikegami

Reputation: 385645

Interpolation happens first, then \Q, \U, \u, \L and \l.

That means

"abc\Qdef$ghi!jkl\Emno"

is equivalent to

"abc" . quotemeta("def" . $ghi . "!jkl") . "mno"

So,

s/\Q$~^/Two/    # not ok   quotemeta($~ . "^")
s/\Q$Sub/Two/   # ok
s/\$\~\^/Two/   # ok
s/\$\Q~^/Two/   # ok

Upvotes: 1

Related Questions