如何在Perl中计算字符? [英] How can I count characters in Perl?

查看:118
本文介绍了如何在Perl中计算字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Perl脚本计算字符串中F和T的数量:

I have the following Perl script counting the number of Fs and Ts in a string:

my $str = "GGGFFEEIIEETTGGG";
my $ft_count = 0;
$ft_count++ while($str =~ m/[FT]/g);
print "$ft_count\n";

是否有一种更简洁的方法来获取计数(换句话说,就是将第2行和第3行结合起来)?

Is there a more concise way to get the count (in other words, to combine line 2 and 3)?

推荐答案

my $ft_count = $str =~ tr/FT//;

请参见 perlop .

如果REPLACEMENTLIST为空,则 SEARCHLIST已复制.后者对于计数非常有用 …

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;
    },
};

        Rate     tr      m
     Rate     m    tr
m   108/s    --  -99%
tr 8118/s 7440%    --

在32个Windows XP上使用ActiveState Perl 5.10.1.1006.

With ActiveState Perl 5.10.1.1006 on 32 Windows XP.

差异似乎很明显

C:\Temp> c:\opt\strawberry-5.12.1\perl\bin\perl.exe t.pl
      Rate      m     tr
m   88.8/s     --  -100%
tr 25507/s 28631%     --

这篇关于如何在Perl中计算字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆