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.
Perl Hash Accessing To access single element of hash, ($) sign is used before the variable name. And then key element is written inside {} braces.
The while/each loop is using for print multiple Perl hash elements. Users can apply the print keyword once and display all hash keys and values. The while/each loop print ordered hash key and value.
You can only store scalar values in a hash. References, however, are scalars. This solves the problem of storing multiple values for one key by making $hash{$key} a reference to an array containing values for $key .
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With