You can simplify all the dereferencing if you use a while loop with each rather than a for loop. With this method, you cannot sort the keys, but in your case, that is OK.
use strict; use warnings; use Test::More tests => 2; my $month_total = 0; my $day_week_total = 0; my $VAR1 = { 'Adam' => { 'days' => 22, 'weeks' => 5, 'total' => 22 }, 'Keas' => { 'total' => 114, 'test' => 2, 'weeks' => 8, 'days' => 107, 'months' => 5 }, 'Tim' => { 'total' => 4, 'weeks' => 5, 'days' => 3, 'months' => 1 }, 'Sum' => { 'total' => 440, 'days' => 365, 'months' => 9 } }; while (my ($name, $hash) = each %$VAR1) { next if $name eq 'Sum'; if (exists $hash->{months}) { $month_total += $hash->{months}; } if (exists $hash->{days} and exists $hash->{weeks}) { $day_week_total += ($hash->{days} + $hash->{weeks}); } } ok($month_total == 6, 'month_total'); ok($day_week_total == 150, 'day_week_total'); OUTPUT: 1..2 ok 1 - month_total ok 2 - day_week_total
Bill

In reply to Re^3: How to loop through hash of hashes and add the values based on condition? by BillKSmith
in thread How to loop through hash of hashes and add the values based on condition? by Sami_R

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.