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

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

Hello Monks,

I'm trying to write this :

$var =~ s/\(//; $var =~ s/\)//;

in one line. I thought it'll be :

$var =~ s/[\(\)]//;

but this only remove the left one.

Thanks.

Have a nice day.

Replies are listed 'Best First'.
Re: regex question
by Skeeve (Parson) on Oct 27, 2005 at 14:33 UTC
    You're missing the g for G-lobal search after the last /.

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

      Hi Skeeve,

      God am I d**b !

      Thanks.

Re: regex question
by Fletch (Bishop) on Oct 27, 2005 at 14:44 UTC

    Also if you're just trying to remove the characters blindly tr/()//d might be a bit quicker (of course having said that someone will immediately post a benchmark showing that some strange new optimization's gone in 5 months ago and now s///g wipes the floor with it . . .).

Re: regex question
by aquarium (Curate) on Oct 27, 2005 at 14:50 UTC
    you also don't escape characters in a character class. your regex (once g is added for global) will strip back slash characters, as well as braces. i.e. should be:
    $var =~ s/[()]//g;
    the hardest line to type correctly is: stty erase ^H
      you also don't escape characters in a character class. your regex (once g is added for global) will strip back slash characters, as well as braces.
      No, it doesn't. There's no need to escape the parens, but it certainly doesn't do any harm:
      $_ = 'foo\bar(baz)'; print "Before: '$_'; "; s/[\(\)]//g; print "After: '$_'\n"; __END__ Before: 'foo\bar(baz)'; After: 'foo\barbaz'
      No backslashes are removed.
      Perl --((8:>*
      you also don't escape characters in a character class.

      That's not very good advice. Sometimes you certainly do need to escape characters in a character class. Take the following for example:

      $ perl -le '$_ = q/f!o@o#b$a%r^b&a*z/; s/[!@#$%^&*]//g; print'

      -sauoq
      "My two cents aren't worth a dime.";
      
        Or, even more drastical, see the difference in these lines:
        perl -e '$_="bjzu-sbtz -abnzo-tbhze-rb zp-ebrzl- bhza-cbkze-r\n";s/[b-z]//g;print'
        vs.
        perl -e '$_="bjzu-sbtz -abnzo-tbhze-rb zp-ebrzl- bhza-cbkze-r\n";s/[b\-z]//g;print'

        s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
        +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

      the hardest line to type correctly is: stty erase ^H

      Type it as: stty erase ^V^H

      Update: I missed the point, which was that you cannot backspace if backspace isn't set correctly.