tags:

views:

408

answers:

3

How do I find the number of keys in a Perl hash variable, like Perl array $#?

+12  A: 
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.

chaos
$#+1 - we will get no of elements . i am meaning that for $#
joe
Ah, I see. Well, I would still recommend `scalar @array` over `$#array + 1`. :)
chaos
is there any particular reason for that
joe
It's a single operation instead of two, and I try to write code that "asks for what it means" instead of arriving at what it means by some slightly-too-clever alternate route.
chaos
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.
Sinan Ünür
Yeah, and that's worth mentioning. Editing per...
chaos
@Krish: `$#arr + 1` will give you the number of elements in the array iff `$[ == 0` (see `perldoc perlvar`)
Sinan Ünür
+1  A: 

we can use like this too

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

 0+(keys %r)
joe
i found this after posted in so
joe
+2  A: 

The following will return one less that the number of keys in your hash. You may like it if you are fond of the $#array-style of doing things (or conciseness):

$#{$hash};

CRITICAL EDIT:

Hold on... this is interesting. It works if you want to use it as an array reference, but not if you use it outside. So it's useful if you want to access the last key of your hash, provided that you've assigned your keys as an array to a temp: Check this out:

%hash = ( "barney" => "dinosaur", "elmo" => "monster");
@array = sort {$a cmp $b} keys %hash;
print $array[$#{$hash}];
# prints "elmo"
Zaid
This answer surprised me, so I tried it out and... it doesn't work.
Dave Hinton
@Dave: Check the critical edit above. Thanks for the heads up.
Zaid
@Zaid: replace `$#{$hash}` with `-1`. `$array[-1]` always means the last element of `@array` (and `$array[-2]` always means the second-to-last, etc). `$hash` is unrelated to `%hash`. In your code, perl sees you using an undefined variable as an array reference, so pretends that it *is* an array reference. Try `use warnings; use strict;` at the beginning and see what perl says then.
Dave Hinton
@Dave: Surprisingly, 'strict' and 'warnings' don't have a problem with this. I've used this in my code without knowing that this could be a potential problem.
Zaid