I am trying to count the characters in a string and found an easy solution counting a single character using the tr operator. Now I want to do this with every character from a to z. The following solution doesn’t work because tr/// matches every character.
my @chars = ('a' .. 'z');
foreach my $c (@chars)
{
$count{$c} = ($text =~ tr/$c//);
}
How do I correctly use the char variable in tr///?
trdoesn’t support variable interpolation (neither in the search list nor in the replacement list). If you want to use variables, you must useeval():That said, a more efficient (and secure) approach would be to simply iterate over the characters in the string and increment counters for each character, e.g.: