$count = scalar keys %hash;
Apparently, this method is optomized in some fashion and significantly faster than iterating through the hash yourself. I wrote a simple sample program to time the outputs:
#!/usr/bin/perl
use Benchmark;
%hash = ( 1 .. 10000 ) ;
timethese 1 << (shift || 10), {
keys => q{ $count = keys %hash },
count => q{ $count = 0 ; $count++ foreach keys %hash }
};
The results of this program are:
Benchmark: timing 1024 iterations of count, keys...
count: 2 wallclock secs ( 2.11 usr + 0.00 sys = 2.11 CPU) @ 485.31/s (n=1024)
keys: 0 wallclock secs ( 0.00 usr + 0.00 sys = 0.00 CPU)
(warning: too few iterations for a reliable count)
This is something that will not work with tied hashes, however. It may return a result depending on what you are tied to, but not nearly as quickly. The reason has to do with the way you have to develop a tied interface. It is worth looking into whether the platform you are working with - be it BerkeleyDB or something else, supports a count function that would be more efficient than an iteration.Now, if you are mucking around in C with perl, there's an HvKeys macro that should return the count, but I don't fully understand it right now, nor do I have the inclination to spend any time figuring it out.
Note that you could shorten your syntax to just:
$count = keys %hash;
but my opinion is to keep the scalar word in there just so you remember what you were doing at a later date. I find when I use shortcuts and don't put a little inline documentation right next to it, I have a hard time interpereting my own code.
Talk About Counting Keys in a Perl Hash
