Your specification for the desired result hash is not quite valid: You cannot have a lone array reference in a hash, only  key => value pairs. This can be fixed by giving the array references a key, for example "values". The result hash would then look like this:

( A => { count => 3, B => { count => 2, values => ["n1", "n2"] }, C => { count => 1, values => ["n1" ] } }, D => { count => 3, E => { count => 2, values => ["n2", "n4"] }, F => { count => 1, values => ["n1" ] } } )

It can easily be generated....

...from the HoH that you already have:

You can transform the existing HoH into the specified result hash, using two (nested) loops, and making use of the fact that  scalar @array gives the number of elements in an array:

my %hoh = ( A => { B => [ "n1", "n2" ], C => [ "n1" ] }, D => { E => [ "n2", "n4" ], F => [ "n1" ] }, ); foreach my $col1 (keys %hoh) { my $count1 = 0; foreach my $col2 (keys %{$hoh{$col1}}) { my $count2 = scalar @{$hoh{$col1}{$col2}}; $hoh{$col1}{$col2} = { count => $count2, values => $hoh{$col1}{$col2} }; $count1 += $count2; } $hoh{$col1}{count} = $count1; }

...from the original data:

If you do the counting directly in the code that generates the HoH in the first place, it's even easier - just increment the counters for both levels as you go along:

my %hoh; while (<DATA>) { chomp; my ($c1, $c2, $c3) = split; $hoh{$c1}{count}++; $hoh{$c1}{$c2}{count}++; push @{$hoh{$c1}{$c2}{values}}, $c3; } __DATA__ A B n1 A B n2 A C n1 D E n2 D E n4 D F n1

---
Edit: Refactored the answer to make it more structured.


In reply to Re: Count number of elements in HoH and sum them for other keys by smls
in thread Count number of elements in HoH and sum them for other keys by Sosi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.