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

hi
i want to remove from a string $str a possible occurrences of characters which have ascii codes :
215,220,224,226,231,232,233,234,235
is it possible to use regular expressions in this case? since such a $str =~ tr/abc//d; will remove the abc chars but the above chars have unclear forms.

Replies are listed 'Best First'.
Re: remove characters by their codes
by kyle (Abbot) on Dec 10, 2007 at 19:43 UTC

    Some other monk will probably post a one-liner, but this should work, and hopefully it's easy to understand. If you don't know of them already, have a look at chr and quotemeta, and maybe ord for good measure.

    my @ascii_be_gone = (215,220,224,226,231,232,233,234,235); my @chars_to_go = map { chr } @ascii_be_gone; my $pattern = join '|', map { quotemeta } @chars_to_go; $str =~ s{$pattern}{}g;
      Since they're characters, not strings, you can use a character class instead of an alternation.
      my @ascii_be_gone = (215,220,224,226,231,232,233,234,235); my @chars_to_go = map { chr } @ascii_be_gone; my ($pattern) = map { qr/[$_]/ } join '', map { quotemeta } @chars_to_ +go; $str =~ s{$pattern}{}g;
Re: remove characters by their codes
by BrowserUk (Patriarch) on Dec 10, 2007 at 19:44 UTC
Re: remove characters by their codes
by Fletch (Bishop) on Dec 10, 2007 at 19:45 UTC

    The \xdd escapes (for hex, or \0dd for octal digits, etc.) documented in perlop (search for "Quote and Quote-like Operators") work within a tr statement.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: remove characters by their codes
by artist (Parson) on Dec 10, 2007 at 19:52 UTC
    If they belong to a particular set, we can do better.