How can I count characters in Perl?

Daniel Standage picture Daniel Standage · Sep 28, 2010 · Viewed 20k times · Source

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

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

Answer

Sinan Ünür picture Sinan Ünür · Sep 28, 2010
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%     --