Malkavian has asked for the wisdom of the Perl Monks concerning the following question: (hashes)

Is there any fast way of finding the number of elements in a hash without first assigning an array of keys of a hash?
Basically, I don't like the overhead of doing the operation:

@array=keys(%hash); $size=$#array;

It just seems a little wasteful. If anyone can point out a quickie answer, I'd be hideously grateful

Cheers,

Malk

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How can I find the number of elements in a hash?
by OeufMayo (Curate) on Mar 09, 2001 at 02:22 UTC

    The easiest way is to have the keys function evaluated in scalar context:

    %hash = ('foo'=>1, 'bar'=>3); $count = keys %hash;
Re: How can I find the number of elements in a hash?
by Bloodelf (Beadle) on Jun 19, 2001 at 02:17 UTC
Re: Size of a hash
by japhy (Canon) on Mar 08, 2001 at 22:09 UTC
    You did that wrong, by the way. You wanted $size = @array, not $#array. And you want to call keys() in scalar context, like it's documented.
      My stupid mistake. RTFM strikes again. Thanks.
Re: How can I find the number of elements in a hash?
by sot3 (Initiate) on Aug 12, 2010 at 19:47 UTC
    Use this: $size = scalar keys %hash;