How do I find the number of keys in a Perl hash variable, like Perl array $#
?
views:
408answers:
3
+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
2009-07-10 11:48:36
$#+1 - we will get no of elements . i am meaning that for $#
joe
2009-07-10 11:55:15
Ah, I see. Well, I would still recommend `scalar @array` over `$#array + 1`. :)
chaos
2009-07-10 12:01:19
is there any particular reason for that
joe
2009-07-10 12:16:36
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
2009-07-10 12:26:36
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
2009-07-10 15:28:01
Yeah, and that's worth mentioning. Editing per...
chaos
2009-07-10 15:30:08
@Krish: `$#arr + 1` will give you the number of elements in the array iff `$[ == 0` (see `perldoc perlvar`)
Sinan Ünür
2009-07-10 15:31:24
+1
A:
we can use like this too
my $keys = keys(%r) ;
print "keys = $keys" ;
0+(keys %r)
joe
2009-07-10 11:52:43
+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
2009-07-10 12:14:45
@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
2009-07-10 16:30:57
@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
2009-07-10 20:16:12