Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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

by kcott (Bishop)
on Oct 29, 2021 at 23:38 UTC ( #11138245=note: print w/replies, xml ) Need Help??


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

G'day vaitor15,

Welcome to the Monastery.

[I see from previous replies that you have modified your post one or more times. In the version that I'm seeing, 430 as a total is incorrect; however, other comments indicate that this was correct at one time. It is impossible for us, and therefore you, to tell which solutions are valid. Please ensure that you understand the issues here (by reading "How do I change/delete my post?") and, in any future posts, clearly indicate updates.]

In my code below, I've laid out the data (as I currently see it) in a manner that makes it more readable and comprehensible. Your current costs (6300+300+30) total 6630.

#!/usr/bin/env perl use strict; use warnings; 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 $total = 0; get_total_cost($VAR1, \$total); printf "Total = %.2f\n", $total; sub get_total_cost { my ($hash_data, $sub_total) = @_; for my $key (keys %$hash_data) { if (ref $hash_data->{$key} eq 'HASH') { next unless keys %{$hash_data->{$key}}; get_total_cost($hash_data->{$key}, $sub_total); } else { if ($key eq 'cost') { $$sub_total += $hash_data->{cost}; } } } return; }

Note that this doesn't care how deep in the hash the 'cost' key is located. It also ignores 'cost2' keys, and any other variant of a key containing 'cost'; if that's not what you wanted, modify the $key eq 'cost' condition (if it's just keys starting with 'cost', index would be the most efficient; otherwise, a regex would probably be the best solution).

Output:

Total = 6630.00

— Ken

Replies are listed 'Best First'.
Re^2: Iterating over hash to find specific key to sum up the cost
by LanX (Sage) on Oct 29, 2021 at 23:55 UTC
    > In the version that I'm seeing, 430 as a total is incorrect;

    yeah but it's probably the total of

    '153-1' => { '135-1' => { '68-4' => { 'cost' => '300.00', 'cost2' => '130.00'

    let's wait for the next update ... ;)

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Log In?
Username:
Password:

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

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



    Results (98 votes). Check out past polls.

    Notices?