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)
Comments
-
Prasad almost 2 years
How do I find the number of keys in a hash, like using
$#
for arrays? -
Prasad almost 15 yearsi found this after posted in so
-
Prasad almost 15 years$#+1 - we will get no of elements . i am meaning that for $#
-
chaos almost 15 yearsAh, I see. Well, I would still recommend
scalar @array
over$#array + 1
. :) -
Prasad almost 15 yearsis there any particular reason for that
-
silbana almost 15 yearsOf 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 thescalar
making this even simpler. -
silbana almost 15 years@Krish:
$#arr + 1
will give you the number of elements in the array iff$[ == 0
(seeperldoc perlvar
) -
David Makogon almost 8 yearsSorry but... how does this differ from the heavily-upvoted, accepted answer, posted 7 years ago, other than using
print
? -
Gray over 4 yearsHow does this answer differ than the accepted answer?