Given ...
Ax~B~xCx~xDx
... emit ...
A~-B-~C~-~D~
I want to replace the ~ characters with - and the x characters with ~.
I could write ...
s/~/-/g;s/x/~/g;
... but that (looks like it) passes over the string twice.
In perl one would replace string without putting much thought into it. You use use the code ' $str =~ s/replace_this/with_this/g; ' - this is a very efficient and easy way to replace a string.
Performing a regex search-and-replace is just as easy: $string =~ s/regex/replacement/g; I added a “g” after the last forward slash. The “g” stands for “global”, which tells Perl to replace all matches, and not just the first one.
Use "transliterate" for replacement based on characters. Try this:
tr/~x/\-~/;
Since you're dealing with single characters, tr/// is the obvious answer:
tr/~x/-~/;
However, you're going to need s/// to deal with longer sequences:
my %subs = ( '~' => '-', 'x' => '~' );
my $pat = join '|', map quotemeta, keys %subs;
s/($pat)/$subs{$1}/g;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With