Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Iterating over hash to find specific key to sum up the cost

by BillKSmith (Monsignor)
on Oct 30, 2021 at 03:06 UTC ( #11138250=note: print w/replies, xml ) Need Help??


in reply to Iterating over hash to find specific key to sum up the cost

Perhaps you want the sum of all values under a given 'cost key' ('68-4' in this case).
use strict; use warnings; use List::Util qw(sum); my $VAR1 = { '153-1' => { '19-4' => { 'cost' => '6300.00', 'cost2' => '630.00' }, '135-1' => { '68-4' => { 'cost' => '300.00', 'cost2' => '130.00' } }, '1069-9' => {}, '35-1' => { '28-4' => { 'cost' => '30.00', 'cost2' => '10.00' } }, }, }; my $cost_key = '68-4'; foreach my $temp1 (values %$VAR1) { foreach my $temp2 (values %$temp1) { next if !exists $temp2->{$cost_key}; print sum( values(%{$temp2->{$cost_key}})); } }

OUTPUT:

430
Bill

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11138250]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2022-05-28 06:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (98 votes). Check out past polls.

    Notices?