in reply to This should be easy: counting letters in a string

I thought of this way:
my @letters = qw (A B C D E F); my $string = "AFTYUBEWTWECRTUTYIYTDDDDRYJURTHJTREEEEEFGSDFF"; foreach (@letters) { my $count = 0; $count ++ while $string =~ /$_/g; print "$_ : $count\n"; } output: A : 1 B : 1 C : 1 D : 5 E : 7 F : 4
But, it looks like the way using 'm//g' is slower than 's///g'. Benchmark:
use Benchmark; my @letters = qw (A B C D E F); my $string = "AFTYUBEWTWECRTUTYIYTDDDDRYJURTHJTREEEEEFGSDFF" x 100; timethese(1000,{ match=>\&match,subst=>\&subst}); sub match{ my $str = $string; foreach (@letters) { my $count = 0; $count ++ while $str =~ /$_/g; # print "$_ : $count\n"; } } sub subst{ my $str = $string; foreach (@letters){ my $count = $str =~ s/$_//g; # print "$_ : $count\n"; } } output: Benchmark: timing 1000 iterations of match, subst... match: 10 wallclock secs ( 2.52 usr + 0.01 sys = 2.53 CPU) @ 39 +5.26/s (n=1000) subst: 2 wallclock secs ( 1.88 usr + 0.01 sys = 1.89 CPU) @ 52 +9.10/s (n=1000)
Hope this helps,