Howard
Howard

Reputation: 19805

Translate string in Perl

In PHP, strtr can accept an input of array and replace all occurrence of key within the string, and the longest keys will be tried first.

Is there equivalant function in Perl?

Upvotes: 0

Views: 389

Answers (2)

MkV
MkV

Reputation: 3096

Rather than manually building up a regex to evaluate, use Data::Munge's list2re function like this:

my $re = list2re sort {length($b) <=> length($a)} keys %h;
$a =~ s/($re)/$h{$1}/g;

Upvotes: 3

Nik
Nik

Reputation: 472

Yep, simple regex:

# Where %h contains your key => value mappings
my $keys = join '|', sort {length($b) <=> length($a)} keys %h;
$a =~ s/($keys)/$h{$1}/g;

Upvotes: 7

Related Questions