my $johndoe_hours = 0; foreach my $month ( keys %main } { $johndoe_hours += $johndoe_hours + $main{$month}{johndoe}; }
If you want to get rid of the error message when {johndoe} does not exist in the hash $main{$month} (that is assuming you are using warnings), you might want to do something like the following instead:my $johndoe_hours = 0; foreach my $month ( keys %main } { $johndoe_hours += $main{$month}{johndoe}; }
my $johndoe_hours = 0; foreach my $month ( keys %main } { if ( exists $main{$month}{johndoe} ) { $johndoe_hours += $johndoe_hours + $main{$month}{johndoe}; } }
update: Fixed code from doubling johndoe's hours.my $johndoe_hours = 0; foreach my $month ( keys %main } { if ( exists $main{$month}{johndoe} ) { $johndoe_hours += $main{$month}{johndoe}; } }
-enlil
In reply to Re: HoH Issue(AKA Iterating over hash elements)
by Enlil
in thread Iterating over hash elements (was: Sorry to bother you)
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |