-2

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]
)
Aman Vidura
  • 85
  • 2
  • 10
  • 2
    What do you mean "by preserving the order of the hash refs?" The order in which they were inserted? Ordered alphabetically? Something else? – ThisSuitIsBlackNot Dec 11 '13 at 22:46
  • You need to use function ref() to determine what type of the reference you have. The keys in the hash has its own order independent of inserting order. You can use sort(keys(%{$hash_ref})). – alex Dec 11 '13 at 22:50
  • @ThisSuitIsBlackNot It's in the order they were inserted – Aman Vidura Dec 11 '13 at 22:53
  • @AmanVidura [iterating-hash-based-on-the-insertion-order](http://stackoverflow.com/questions/3638690/iterating-hash-based-on-the-insertion-order) – chrsblck Dec 11 '13 at 23:19
  • In the upper level you have an array of the ( key1, href1, key2, href2, ... ), nd you can go though using indexed access to this array. However, in the second level you have only the hash and there is no preserved order. Replace it by arrayref [] and you'll have order. – alex Dec 11 '13 at 23:41

1 Answers1

1

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.

Tim Pierce
  • 5,514
  • 1
  • 15
  • 31