Perl: Count number of a specific character in a string

I needed to count how many * characters were in a string, so I wrote this simple function.

sub char_count {
    my ($needle,$str) = @_;
    my $len = length($str);
    my $ret = 0;

    for (my $i = 0; $i < $len; $i++) {
        my $found = substr($str,$i,1);

        if ($needle eq $found) { $ret++; }
    }

    return $ret;
}

You can also write it using tr:

sub char_count {
    my ($needle,$haystack) = @_;
    my  $count = $haystack =~ tr/$needle//;

    return $count;
}
Leave A Reply - 2 Replies
Replies
john 2013-10-02 04:06pm - No Email - Logged IP: 87.173.189.94
sub char_count { scalar grep {$_ eq $_[0]} split(//, $_[1]) }

my $str = "Don't know what Larry would say, but I think this is a more perl-style version of your function."; 

printf("The character 'o' is contained %d times in the stringn", char_count("o", $str)); 
Steven Haryanto 2013-10-18 03:30am - stevenharyanto@... - Logged IP: 203.130.198.32

Many people write:

$count = 0; $count++ while $str =~ /needle/g;

You can also write:

$count = @{[ $str =~ /needle/g ]};

All content licensed under the Creative Commons License