In perl, how to replace a character set with another character set in one pass?

Considering...

Ax~B~xCx~xDx

... emit ...

A~-B-~C~-~D~

I want to replace ~ characters with characters - and x with ~ character.

I could write ...

s/~/-/g;s/x/~/g; 

... but it (looks like this) goes over the line twice.

+5
source share
2 answers

Use "transliterate" for character based substitutions. Try the following:

tr/~x/\-~/;
+14
source

Since you are dealing with single characters, tr /// is the obvious answer:

tr/~x/-~/;

However, you will need s /// to handle longer sequences:

my %subs = ( '~' => '-', 'x' => '~' );
my $pat = join '|', map quotemeta, keys %subs;
s/($pat)/$subs{$1}/g;
+2
source

All Articles