Adding Values ​​to a Hash (Perl)

I want to add values ​​from the hash that I 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 quite sure where I am going wrong. I am new to Perl.

EDIT: I tried using the "+" operator, but I got an 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 similar to Key value cat 2 dog 4 rat 1

So, I am trying to compose all the values, so I can take the average.

EDIT 2: The actual fix is ​​contained in the comments I need to make my $ value_count = 0. This fixed everything. Thank you all. I think this is an important issue that needs to be addressed, and I think it might be useful for someone else, so I'm going to leave it.

+6
source share
2 answers

To use the sum function, you need the List::Util package. But in this case, this is not necessary, since you can use the + operator:

 $value_count = $value_count + $words{$key}; # or $value_count += $words{$key}; 

In fact, you can use sum and avoid a loop. This is the solution you should use:

 use List::Util 'sum'; my $value_count = sum values %words; 

The values function returns the hash values ​​in the form of a list, and sum sums this list. If you do not want to summarize all the keys, use a hash fragment:

 use List::Util 'sum'; my $value_count = sum @words{@keys}; 
+20
source

You should be fine if you replace:

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

FROM

 $value_count += $words{key}; 
+3
source

All Articles