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

Hi Monks!

How can these lines of regular expression be combined into one line?
$phone =~ s/\(//g; $phone =~ s/\)/-/g;

Test code:
... my $phone = "(xxx)1234-0000"; $phone =~ s/\(//g; $phone =~ s/\)/-/g; print $phone; # Result: xxx-1234-0000

Thanks for looking!

Replies are listed 'Best First'.
Re: Combining two actions in RegExp
by jwkrahn (Abbot) on Jan 23, 2018 at 19:43 UTC

    By using tr/// instead of a regular expression:

    $ perl -le' my $phone = "(xxx)1234-0000"; $phone =~ tr/)(/-/d; print $phone; ' xxx-1234-0000
      That works, can spaces be removed from the string if found using TR?
      e.g. my $phone = "(xxx) 1234-0000";
        $phone =~ tr/)(/-/d; says to delete the parentheses and also replace the closing paren with '-';

        To also delete any spaces, you could use $phone =~ tr/)(\x20/-/d; where '\x20' is the hex value of a 'space'. You could also use $phone =~ tr/)( /-/d; without the hex value of a space and just use a literal space instead. (The hex version just makes the 'space' more explicit).