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

PerlHash

Perl Problem Overview


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

Perl Solutions


Solution 1 - Perl

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 - Perl

we can use like this too

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

 0+(keys %r) 

Solution 3 - Perl

But not after Perl 5.10:

use feature ":5.10";
my %p = ();
say $#%p;

# $# is no longer supported

and worse:

use feature ":5.10";
my %p = (a=>1, b=>2, c=>3);
say $#{%p};

# -1

Solution 4 - Perl

print scalar keys %hash;

or

$X = keys %hash;
print $X;

keys %hash returns the value of keys in the list context that further changes into the scalar context (when assigning to scalar variable).

Solution 5 - Perl

This will work in easy way and for any size of a hash.

print scalar keys %hash;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjoeView Question on Stackoverflow
Solution 1 - PerlchaosView Answer on Stackoverflow
Solution 2 - PerljoeView Answer on Stackoverflow
Solution 3 - Perluser846969View Answer on Stackoverflow
Solution 4 - PerlSandeep_blackView Answer on Stackoverflow
Solution 5 - PerlSudheerView Answer on Stackoverflow