Hello!
You already has been provided with more than one way to do this, and I want to participate in this game too. Here's another way - just like you wanted - using map:
use strict; my $weapons_ref = { dagger => { cost => 8, damage => 4, armor => 0 }, shortsword => { cost => 10, damage => 5, armor => 0 }, warhammer => { cost => 25, damage => 6, armor => 0 }, longsword => { cost => 40, damage => 7, armor => 0 }, greataxe => { cost => 74, damage => 8, armor => 0 }, }; my $sum_cost; my $sum_damage; my $sum_armor; map { $sum_damage += $weapons_ref->{$_}->{damage}; $sum_cost += $weapons_ref->{$_}->{cost}; $sum_armor += $weapons_ref->{$_}->{armor} } keys %{ $weapons_ref }; print join(' ',$sum_cost, $sum_damage, $sum_armor), '\n';
157 30 0
This code is a little bit specific, while I think we should move towards more general code, to make reusing it more simpler. Let's refactor it:
use strict; use Data::Dumper; my $weapons_ref = { dagger => { cost => 8, damage => 4, armor => 0 }, shortsword => { cost => 10, damage => 5, armor => 0 }, warhammer => { cost => 25, damage => 6, armor => 0 }, longsword => { cost => 40, damage => 7, armor => 0 }, greataxe => { cost => 74, damage => 8, armor => 0 }, }; my $sum_result; my @sum_fields = qw/cost damage armor/; map { my $name = $_; map { $sum_result->{$_} += $weapons_ref->{$name}->{$_} } @sum_fields } keys %{ $weapons_ref }; print Dumper($sum_result);
$VAR1 = { 'armor' => 0, 'cost' => 157, 'damage' => 30 };
Next step is to refactor this code to a function, which will receive a hash, an array of fields that we like to sum, and return a hash with sums.
In reply to Re: using ref to hash of hash effectively
by alexander_lunev
in thread using ref to hash of hash effectively
by kalee
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |