http://qs321.pair.com?node_id=140184


in reply to Re: Range of chars except one
in thread Range of chars except one

This can be made even simpler. Remember that if a character is listed in a tr/// searchlist more than once, only the first occurance is meaningful. This means you can do something like:
$string =~ tr/\n\000-\037/\n/d;
(Note I'm using octal here). This specifies that the newline character is replaced by itself, while everything else in that range is deleted.

There are three advantages to this method: <NL>

  • It's (IMHO) cleaner and easier to read.
  • It's easier to modify, e.g. to exempt additional characters from being deleted.
  • It doesn't care what character is used for newline on the current platform. For example, I seem to remember that \n and \r have their meanings reversed on one platform (Macintosh?) because the platform standard is to use CR for line breaks. </NL>
  • Replies are listed 'Best First'.
    Re: Re: Re: Range of chars except one
    by Anonymous Monk on Jan 21, 2002 at 08:47 UTC
      True i thought about tr/// too... but "a range of chars except one", could also be read "a range of chars PLUS one" (i like to reverse things up). tr/// also offer a complement modifier to it.
      So when i need to delete chars, it seems more simple to write the one i actually want to keep, preventing me to forget some:
      $_ = "123,Let's keep letters!\nAnd new lines..."
      tr/A-Za-z \n//cd;
      print;
      will print:
      Lets keep letters
      And new lines

      Creating that range could be easier...

      It's just my two cents.
      Freddo