in reply to Re^2: How to loop through hash of hashes and add the values based on condition?
in thread How to loop through hash of hashes and add the values based on condition?

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
  • Comment on Re^3: How to loop through hash of hashes and add the values based on condition?
  • Download Code

Replies are listed 'Best First'.
Re^4: How to loop through hash of hashes and add the values based on condition?
by Sami_R (Sexton) on Jan 08, 2020 at 19:42 UTC
    Hi Bill,

    Thank you so much for the support, code really helped!