Search code examples
regexstringperlcharacter

Better way to remove specific characters from a Perl string


I have dynamically generated strings like @#@!efq@!#!, and I want to remove specific characters from the string using Perl.

Currently I am doing something this (replacing the characters with nothing):

$varTemp =~ s/['\$','\#','\@','\~','\!','\&','\*','\(','\)','\[','\]','\;','\.','\,','\:','\?','\^',' ', '\`','\\','\/']//g;

Is there a better way of doing this?


Solution

  • You've misunderstood how character classes are used:

    $varTemp =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;
    

    does the same as your regex (assuming you didn't mean to remove ' characters from your strings).

    Edit: The + allows several of those "special characters" to match at once, so it should also be faster.