in reply to Re: Count values of the inner hash?
in thread Count values of the inner hash?

Just want to add a bit of explanation to Limbic~Region's solution above in case anybody want's to understand what the code is doing. What the above code does is combining several steps into one:
# retrieve a list of keys my @keys = keys %{ $Prod{ref261} }; # return the number of elements in the list my $count = scalar @keys;

Combining the two steps gives:
my $count = scalar keys %{ $Prod{ref261} };

And you can omit "scalar" because perl knows that the left hand side of the assignment is a scalar. Thus gives the simplified form of:
my $count = keys %{ $Prod{ref261} };

Replies are listed 'Best First'.
Re^3: Count values of the inner hash?
by bart (Canon) on Mar 28, 2004 at 11:21 UTC
    Except, well... keys happens to return the number of keys in scalar context. There is no intermediate array — not even a temporary one. The fact that you get the same result as if there was, is by design, because it's more or less a result like what Perl programmers would expect, and no other, more interesting possible result has been conceived.

    For example, a hash in scalar context might have returned the total number of keys and values, hence double the number of keys — but it doesn't, as the language designers thought that stats about the internal state of the hash itself were more interesting, especially as there is no other way (barring XS) to get at them. (And no, noone hardly ever uses it, except for debugging and illustrative purposes.)

    To illustrate:

    Beginning Perl programmers better learn to recognize the fact that functions/keywords may return unrelated results depending on the calling context, scalar vs. list. You may compare the results to other results for learning purposes, like Roger did, but you must recognize the fact that these similarities in behaviour are incidental, and sooner rather than later. When in doubt, you better get into the habit of looking up what a function/keyword returns in scalar/list context, instead of to speculate. Oh, and there's no such thing as a list in scalar context. (Yes, that's a quote. :))