my $ft_count = $str =~ tr/FT//;
见perlop。
如果 REPLACEMENTLIST 为空,则复制 SEARCHLIST。后者对于计算类中的字符很有用……
$cnt = $sky =~ tr/*/*/; # count the stars in $sky
$cnt = tr/0-9//; # count the digits in $_
这是一个基准:
use strict; use warnings;
use Benchmark qw( cmpthese );
my ($x, $y) = ("GGGFFEEIIEETTGGG" x 1000) x 2;
cmpthese -5, {
'tr' => sub {
my $cnt = $x =~ tr/FT//;
},
'm' => sub {
my $cnt = ()= $y =~ m/[FT]/g;
},
};
率 tr m
速率 m tr
米 108/s -- -99%
tr 8118/s 7440% --
在 32 Windows XP 上使用 ActiveState Perl 5.10.1.1006。
差异似乎更明显
C:\Temp> c:\opt\strawberry-5.12.1\perl\bin\perl.exe t.pl
速率 m tr
米 88.8/s -- -100%
tr 25507/s 28631% --