Reputation: 19805
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
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
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