开发者

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?


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜