Search code examples
perl

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.


Solution

  • 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;