1834022 Members
2312 Online
110063 Solutions
New Discussion

Re: Perl hash

 
Lyn Reynolds
Occasional Contributor

Perl hash

Does anyone know how I obtain the sums of a perl hash by key ?

Thanks
2 REPLIES 2
Ralph Grothe
Honored Contributor

Re: Perl hash

Could you please clarify what you mean?

If you mean to get all the keys of a hash
that would simply be

@keys = keys %hash;

Or do you want to sum up the values?

map $sum+=$_, values %hash;
Madness, thy name is system administration
James R. Ferguson
Acclaimed Contributor

Re: Perl hash

Hi Lyn:

There are many ways. In addition to Ralph's you could do:

# perl -le '%val=("a"=>10,"b"=>20,"c"=>30);for $key (keys %val) {$sum+=$val{$key}};print $sum'
60

# perl -le '%val=("a"=>10,"b"=>20,"c"=>30);$sum+=$val while (($key,$val)=each %val);print $sum'
60

Regards!

...JRF...