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

Hi, I'm new to perl and I'm trying to modify some perl code that processes text going out of an SMS gateway. Currently it suppresses all control characters using this line:
$msg =~ s/[[:cntrl:]]+/ /sg; #(remove CR LF, etc. ORIGINAL LINE)
I want to allow newlines thru but still suppress the other control chars in case they cause trouble with the SMS. Thinking of trying something like:
$msg =~ s/[\n\r]/[~^]/sg; $msg =~ s/[[:cntrl:]]+/ /sg; #(remove CR LF, etc. ORIGINAL LINE) $msg =~ s/[~^]/[\n\r]/sg;
Is there a cleaner way to do it? Would it be better to use tr rather than s ? Can I exclude ranges of chars rather than substituting?

Replies are listed 'Best First'.
Re: CR's and other control chars
by ikegami (Patriarch) on Apr 16, 2009 at 05:06 UTC

    [ PerlMonks Discussion is for discussions about PerlMonks. I moved your post to Seekers of Perl Wisdom ]

    /[[:cntrl:]]/ is equivalent to /[^[:^cntrl:]]/, so

    # Replace everything except non-controls, CR and LF. $msg =~ s/[^[:^cntrl:]\r\n]+/ /g;

    The "s" modifier is useless since "." isn't being used.

      Thank you.