If the character is persistent, best of all:
my $count = $str =~ tr/y//;
If the character is a variable, I would use the following:
my $count = length( $str =~ s/[^\Q$char\E]//rg );
I would only use the following if I wanted compatibility with versions of Perl older than 5.14 (since it is slower and uses more memory):
my $count = () = $str =~ /\Q$char/g;
The memory is not used below, but may be a little slower:
my $count = 0; ++$count while $str =~ /\Q$char/g;
source share