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

thank you so much. I was a bit confused at the beginning: I thought that you had to specify a starting value for $hoh{$c1}{$c2}{count}. By the way, and I know I'm going a bit astray of the initial question, but what if I wanted to start that count at 5? Would specifying

$hoh{$c1}{count}=5;

work if I specified it before incrementing in your while loop? Thanks!

Replies are listed 'Best First'.
Re^3: Count number of elements in HoH and sum them for other keys
by smls (Friar) on Jun 03, 2014 at 13:21 UTC
    I thought that you had to specify a starting value for $hoh{$c1}{$c2}{count}.

    When you dereference or modify a non-existing array or hash element, it will automatically "spring to life", including all the necessary intermediate hashes/arrays. For example:

    my %test; $test{a}[2]{b} = 'Hello'; # %test now contains: # ( a => [ undef, # undef, # { b => "Hello" } ] )

    It's called autovivification, and it's one of the nice features that make Perl special... :)   See Wikipedia and perlreftut for more info.

    In addition, the ++ (auto-increment) operator silently treats undef as 0. So you don't need to specify an initial value.


    what if I wanted to start that count at 5?

    One solution would be to create the hash first, and then use another loop to add 5 to each counter.

    Alternatively, you can do a check inside the loop (before incrementing!) to see if the counter has already been incremented previously, and if not, initialize it with the number 5:

    if (!$hoh{$c1}{count}) { $hoh{$c1}{count} = 5; } # verbose form
    $hoh{$c1}{count} ||= 5; # shortcut

    (See C style Logical Or and Assignment Operators.)