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. :))


In reply to Re^3: Count values of the inner hash? by bart
in thread Count values of the inner hash? by Anonymous Monk

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.