Pradnya Deshmukh
Pradnya Deshmukh

Reputation: 91

How to escape all special characters in a string (along with single and double quotes)?

E.g:

$myVar="this#@#!~`%^&*()[]}{;'".,<>?/\";

I am not able to export this variable and use it as it is in my program.

Upvotes: 9

Views: 28640

Answers (3)

zdim
zdim

Reputation: 66873

This is what quotemeta is for, if I understand your quest

Returns the value of EXPR with all non-"word" characters backslashed. (That is, all characters not matching /[A-Za-z_0-9]/ will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the \Q escape in double-quoted strings.

Its use is very simple

my $myVar = q(this#@#!~`%^&*()[]}{;'".,<>?/\\);
print "$myVar\n";

my $quoted_var = quotemeta $myVar;
print "$quoted_var\n";

Note that we must manually escape the last backslash, to prevent it from escaping the closing delimiter. Or you can tack on an extra space at the end, and then strip it (by chop).

my $myVar = q(this#@#!~`%^&*()[]}{;'".,<>?/\ );
chop $myVar;

Now transform $myVar like above, using quotemeta.

I take the outside pair of " to merely indicate what you'd like in the variable. But if they are in fact meant to be in the variable then simply put it all inside q(), since then the last character is ". The only problem is a backslash immediately preceding the closing delimiter.

If you need this in a regex context then you use \Q to start and \E to end escaping.

Upvotes: 5

mkHun
mkHun

Reputation: 5927

Use q to store the characters and use the quotemeta to escape the all character

my $myVar=q("this#@#!~`%^&*()[]}{;'".,<>?/\");
$myVar = quotemeta($myVar);

print $myVar;

Or else use regex substitution to escape the all character

my $myVar=q("this#@#!~`%^&*()[]}{;'".,<>?/\");
$myVar =~s/(\W)/\\$1/g;
print $myVar;

Upvotes: 10

ssr1012
ssr1012

Reputation: 2589

Giving Thanks to:

What's between \Q and \E is treated as normal characters, not regexp characters. For example,

 '.' =~ /./;      # match
 'a' =~ /./;      # match
 '.' =~ /\Q.\E/;  # match
 'a' =~ /\Q.\E/;  # no match

It doesn't stop variables from being interpolated.

 $search = '.';
 '.' =~ /$search/;      # match
 'a' =~ /$search/;      # match
 '.' =~ /\Q$search\E/;  # match
 'a' =~ /\Q$search\E/;  # no match

Upvotes: 1

Related Questions