A friend queried:
I’ve got a hash array and I want to determine the number of keys in the array. what’s the best way to do so?
This is an interesting question. I can think of a one definite way to do it:
@z = keys %foo ; $nkeys = $#z + 1 ;
…but none of the various apparently-perl-orthogonal ways to get this data seemed to work.
I tried $#foo, which just yielded -1; then I tried scalar %foo which yielded something odd, and (worse) nondeterministic:
$ cat z
$f{“1”} = 1;
$f{“2”} = 1;
$f{“3”} = 1;
$f{“4”} = 1;
$f{“5”} = 1;
$f{“6”} = 1;
$f{“7”} = 1;
print scalar(%f), “\n”;
$ perl z
5/8
$ perl z
6/8
$ perl z
4/8
…which I suspect reflects some hashing statistics. So, either we’d need to use the “keys” trick above, or something like
@z = %foo ; $nkeys = ($#z+1)/2 ;
Does anyone know a faster way?
Leave a Reply