How can I find the number of keys in a hash in Perl?
PerlHashPerl 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;