Kirs Kringle
Kirs Kringle

Reputation: 929

Adding up the values in a hash (Perl)

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.

Upvotes: 9

Views: 11253

Answers (2)

Tim
Tim

Reputation: 14154

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};

Upvotes: 23

DarkAjax
DarkAjax

Reputation: 16223

You should be fine if you replace:

$value_count = sum($words{key}, $value_count);

With:

$value_count += $words{key};

Upvotes: 4

Related Questions