How can I find the number of keys in a hash in Perl?

76,054

Solution 1

scalar keys %hash

or just

keys %hash

if you're already in a scalar context, e.g. my $hash_count = keys %hash  or  print 'bighash' if keys %hash > 1000.

Incidentally, $#array doesn't find the number of elements, it finds the last index. scalar @array finds the number of elements.

Solution 2

we can use like this too

my $keys = keys(%r) ;
print "keys = $keys" ;

 0+(keys %r) 
Share:
76,054
Prasad
Author by

Prasad

I am back

Updated on July 09, 2022

Comments

  • Prasad
    Prasad almost 2 years

    How do I find the number of keys in a hash, like using $# for arrays?

  • Prasad
    Prasad almost 15 years
    i found this after posted in so
  • Prasad
    Prasad almost 15 years
    $#+1 - we will get no of elements . i am meaning that for $#
  • chaos
    chaos almost 15 years
    Ah, I see. Well, I would still recommend scalar @array over $#array + 1. :)
  • Prasad
    Prasad almost 15 years
    is there any particular reason for that
  • silbana
    silbana almost 15 years
    Of course, if you use keys in scalar context, e.g. in an assignment to a scalar or in a conditional, you do not even need the scalar making this even simpler.
  • silbana
    silbana almost 15 years
    @Krish: $#arr + 1 will give you the number of elements in the array iff $[ == 0 (see perldoc perlvar)
  • David Makogon
    David Makogon almost 8 years
    Sorry but... how does this differ from the heavily-upvoted, accepted answer, posted 7 years ago, other than using print?
  • Gray
    Gray over 4 years
    How does this answer differ than the accepted answer?