Karem
Karem

Reputation: 111

Sum multiple keys of hash in one line

I need to sum differents keys of the hash in one line instead of using foreach.

If i have a hash:

%a = (
 a => 4,
 b => 3,
 c => 7,
 d => 2,
 e => 4
);

For example: $a{a d e} output: 10

It could be possible or I need a foreach??

Thanks

Upvotes: 1

Views: 184

Answers (2)

mpapec
mpapec

Reputation: 50647

my $sum = 0;
$sum += $_ for @a{qw( a d e )};

print $sum, "\n";

Upvotes: 1

mob
mob

Reputation: 118605

Possible with hash slice notation

use List::Utils 'sum';
$the_sum = sum( @a{"a","d","e"} );

Upvotes: 5

Related Questions