我有以下 Perl 脚本计算字符串中 Fs 和 Ts 的数量:
my $str = "GGGFFEEIIEETTGGG";
my $ft_count = 0;
$ft_count++ while($str =~ m/[FT]/g);
print "$ft_count\n";
有没有更简洁的方法来获得计数(换句话说,将第 2 行和第 3 行结合起来)?
最佳答案
my $ft_count = $str =~ tr/FT//;
见 perlop .
If the REPLACEMENTLIST is empty, the SEARCHLIST is replicated. This latter is useful for counting characters in a class …
$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% --
关于regex - 如何计算 Perl 中的字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3813768/