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?
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;
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;
精彩评论