Shaveta_Chawla has asked for the wisdom of the Perl Monks concerning the following question:

How can i remove all the special characters from a string. Suppose the string is::

$str = per#lm-on%ks&perl$*wis(+dom)

Replies are listed 'Best First'.
Re: Removing Special Characters
by moritz (Cardinal) on Nov 01, 2011 at 08:03 UTC
      For a banker "%" might not be special. And we are not even touching the subject of Unicode.

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Removing Special Characters
by dsheroh (Monsignor) on Nov 01, 2011 at 08:49 UTC
    Step 1: Define which characters you consider to be "special".
      Howdy!

      Step 1 (alternate): Define the set of characters that are not "special".

      It may be simpler to define the characters you want to keep rather than the ones to exclude. See also the tr///dc solution above.

      yours,
      Michael
Re: Removing Special Characters
by MVS (Monk) on Nov 01, 2011 at 07:50 UTC

    One possibility would be to use a regular expression to remove the characters you don't want:

    $str =~ s/[#\-%&\$*+()]//g;

    If you want to remove everything except alphanumeric characters and underscores, you can simplify it like this:

    $str =~ s/\W//g;
Re: Removing Special Characters
by Anonymous Monk on Nov 01, 2011 at 19:24 UTC