Perl dynamic hash traversal

163 views Asked by At

A hash of (0 or more levels of hash refs of) array refs of hash refs. Note that the level above the leaf nodes will always be array refs, even if they only have one element.

I need to fetch the aggregate sum of VALUE (in an array of array ref) by preserving the order of the hash refs (In the order of insertion).

Examples :

1)

(
   A => {
           A1 => [
                { VALUE => 10 },
                { VALUE => 20 }
            ],
           B1 => [ 
                { VALUE => 30 } 
           ],
        },
   B => {
            A1 => [ 
                { VALUE => 10 } 
            ],
            B1 => [ 
                { VALUE => 5  } 
            ],
        },
   C => {
            A1 => [ 
                { VALUE => 100 } 
            ],
        },
)

The required output of the above structure will be - 

(
    [A, A1, 30],
    [A, B1, 30], 
    [B, A1, 10],
    [B, B1, 5],
    .
    .
    .
    .
)

2)

(
    A => [
            { VALUE => 10 },
            { VALUE => 20 }
        ],
    B => [ 
            { VALUE => 30 } 
        ],
)       

The required output of the above structure will be - 

(
    [A, 30],
    [B, 30]
)
1

There are 1 answers

0
Tim Pierce On

You need to write a function that will walk your hash structure and compute the necessary sums. For each key in the hash, it needs to make this decision:

  • If the value of this key is a list ref, then sum up the VALUE elements in the hashes in this list and return [key, sum]

  • If the value of this hash is a hash ref, then recurse into that hash. If we got a list back from it, append it to our current output and continue.

  • At the top level (depth 0), print out each list that's returned.

There are a number of details that still need to be resolved, but that ought to get you started on the right track.