Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Combining two actions in RegExp

by Anonymous Monk
on Jan 23, 2018 at 19:29 UTC ( #1207772=perlquestion: print w/replies, xml ) Need Help??

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 (Monsignor) 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).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1207772]
Approved by herveus
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2021-05-08 16:11 GMT
Find Nodes?
    Voting Booth?
    Perl 7 will be out ...

    Results (96 votes). Check out past polls.