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