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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.