I suspect they may be asking for the number of hash elements in a particular hash. If so, perlfaq4 comes to the rescue:

How can I know how many entries are in a hash?

If you mean how many keys, then all you have to do is take the scalar sense of the keys() function:

$num_keys = scalar keys %hash;

In void context, the keys() function just resets the iterator, which is faster for tied hashes than would be iterating through the whole hash, one key-value pair at a time.

In other words, it's better to use the above than to use something like these:

$number = grep(//, keys %hash); for (keys %hash) { $number++; }

However, grep is a good solution if you want something more specific, for example:

## Find the number of elements that are defined: $number = grep(defined $hash{$_}, keys %hash); ## Find the number of elements that are "true": $number = grep($_, values %hash); ## Find the number of elements where the key equals the value: $number = grep($_ eq $hash{$_}, keys %hash);

In reply to Re: getting the number of hashes by turnstep
in thread getting the number of hashes by damian

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.