Search code examples
perlperl-data-structures

loop through a complex hash structure


I have the following hashed structure $chainStorage{$R1}{$S1}{$C1} = \@A1

$chainStorage = {
        'ACB' => {
               'E' => {'06' => [100, 200, 95]}
               'B' => {'23' => [20, 1000, 05, 30]}
        },
        'AFG' => {
               'C' => { '24' => [18, 23, 2300, 3456]}
        },
        'HJK' => {
               'A' => {'12' => [24, 25, 3200, 5668]}
               'D' => {'15' => [168]}
        }
}; 

For example, ACB corresponds to two arrays,[100, 200, 95] and [20, 1000, 05, 30] while E corresponds to [100, 200, 95] only.

Right now, I need to add all of the elements in the array corresponding to the first-level key, e.g., ACB, together.

In other words, in another hash structure, I want ACB corresponds to

100+200+95 + 20+1000+05+30 = 1450

How to implement this functionality over $chainStorage?


Solution

  • You could do something like:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use Data::Dump qw(dump);
    
    my $chainStorage = {
            'ACB' => {
                   'E' => {'06' => [100, 200, 95]},
                   'B' => {'23' => [20, 1000, 05, 30]}
            },
            'AFG' => {
                   'C' => { '24' => [18, 23, 2300, 3456]}
            },
            'HJK' => {
                   'A' => {'12' => [24, 25, 3200, 5668]},
                   'D' => {'15' => [168]}
            }
    }; 
    
    
    while (my($k,$v) = each %$chainStorage) {
        my $sum = 0;
        while (my($k2,$v2) = each%$v) {
            while (my($k3,$v3) = each %$v2) {
                foreach (@$v3) {
                    $sum += $_;
                }
            }
        }
        $chainStorage->{$k} = $sum;
    }
    dump$chainStorage;
    

    output:

    { ACB => 1450, AFG => 5797, HJK => 9085 }