Adding up the values in a hash (Perl)
To use the sum
function, you need the List::Util
package. But that isn't needed in this case, as you can use the +
operator:
$value_count = $value_count + $words{$key};
# or $value_count += $words{$key};
In fact, you could use sum
and avoid the loop. This is the solution you should use:
use List::Util 'sum';
my $value_count = sum values %words;
The values
function returns the values of a hash as a list, and sum
sums that list. If you don't want to sum over all keys, use a hash slice:
use List::Util 'sum';
my $value_count = sum @words{@keys};
You should be fine if you replace:
$value_count = sum($words{key}, $value_count);
With:
$value_count += $words{key};