How can I count characters in Perl?

后端 未结 4 442
长发绾君心
长发绾君心 2021-01-11 12:09

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/         


        
4条回答
  •  独厮守ぢ
    2021-01-11 12:49

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

    See 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 $_
    

    Here's a benchmark:

    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%    --

    With ActiveState Perl 5.10.1.1006 on 32 Windows XP.

    The difference seems to be starker with

    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%     --

提交回复
热议问题