Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Iterating over hash to find specific key to sum up the cost (updated!)

by haukex (Bishop)
on Oct 29, 2021 at 19:24 UTC ( #11138234=note: print w/replies, xml ) Need Help??


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

Final Update: When I replied, the code in the OP did not compile, as one of the four closing braces of $VAR1 was missing, leading me to have to make an assumption of what the data structure looks like. The unmarked update to the OP has now invalidated my code below. Plus, the first nested hash was as shown below instead of the current '19-4' => { 'cost' => '6300.00', 'cost2' => '630.00' }, so the sum of the cost keys was indeed originally 430 as OP expects. vaitor15: It is uncool to update a node in a way that renders replies confusing or meaningless.

Note what you've posted here is not runnable. See How do I post a question effectively? Update 2: Because it's not runnable, I've had to guess as to what your data structure looks like, but as LanX points out in his reply, other interpretations are possible. Please clarify what your real input data looks like. /Update

You should read the Perl Data Structures Cookbook (in particular Access and Printing of a HASH OF HASHES) and the Perl References Tutorial to learn how to work with nested data structures like these. Basically, you can use keys to loop over the keys of each level of hashes - this should be enough to get you started:

use warnings; use strict; my %result = ( "1069-9" => {}, "135-1" => { "68-4" => { cost => "300.00", cost2 => "130.00" } }, "153-1" => { "19-4" => { cost => "100.00", cost2 => "30.00" } }, "35-1" => { "28-4" => { cost => "30.00", cost2 => "10.00" } }, ); for my $k1 ( keys %result ) { for my $k2 ( keys %{ $result{$k1} } ) { if ( exists $result{$k1}{$k2}{cost} ) { print "$k1 / $k2 / $result{$k1}{$k2}{cost}\n"; } } }

Update: I used exists in the above code to check for the existence of the cost key because you said "find sum of value when cost key is found". I should add that, depending on what values are possible in your input data, you may want to check for definedness or truth instead.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (2)
As of 2022-01-22 18:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (63 votes). Check out past polls.

    Notices?