I want to add up the values from a hash that I have created.
my $value_count;
foreach my $key (@keys) {
$value_count = sum($words{key}, $value_count);
}
However when I run this I get
Undefined subroutine &main::sum called at C:/Users/Clayton/workspace/main/Main.pl line 54, <$filehandle1> line 174.
I’m not really sure where I am going wrong here. I’m new to Perl.
EDIT: I tried using just + operator but I get the error
Use of uninitialized value in addition (+) at C:/Users/Clayton/workspace/main/Main.pl line 54, <$filehandle1> line 174.
Pretty much my hash is like
Key Value
cat 2
dog 4
rat 1
So I’m trying to add up all the values so I can take an average.
EDIT 2: The actual fix is in the comments I needed to make my $value_count = 0. That fixed everything. Thank you all. I think this is an important issue to be resolved and I think it could be useful for someone else so I’m going to leave it.
To use the
sumfunction, you need theList::Utilpackage. But that isn’t needed in this case, as you can use the+operator:In fact, you could use
sumand avoid the loop. This is the solution you should use:The
valuesfunction returns the values of a hash as a list, andsumsums that list. If you don’t want to sum over all keys, use a hash slice: