Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In perl, how do I replace a set of characters with a different set of characters in a single pass?

Tags:

perl

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.

like image 921
Thomas L Holaday Avatar asked Feb 09 '12 19:02

Thomas L Holaday


People also ask

How do I replace a string with another string in Perl?

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.

How do I search and replace in Perl?

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.


2 Answers

Use "transliterate" for replacement based on characters. Try this:

tr/~x/\-~/;
like image 154
m0skit0 Avatar answered Sep 23 '22 02:09

m0skit0


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;
like image 25
ikegami Avatar answered Sep 21 '22 02:09

ikegami