Perl FAQ 5.7: How can I know how many entries are in an associative array?

Perl FAQ 5.7

How can I know how many entries are in an associative array?

While the number of elements in a @foobar array is simply @foobar when used in a scalar, you can't figure out how many elements are in an associative array in an analogous fashion. That's because %foobar in a scalar context returns the ratio (as a string) of number of buckets filled versus the number allocated. For example, scalar(%ENV) might return ``20/32''. While perl could in theory keep a count, this would break down on associative arrays that have been bound to dbm files.

However, while you can't get a count this way, one thing you can use it for is to determine whether there are any elements whatsoever in the array, since ``if (%table)'' is guaranteed to be false if nothing has ever been stored in it.

As of perl4.035, you can says

    $count = keys %ARRAY;

keys() when used in a scalar context will return the number of keys, rather than the keys themselves.


Other resources at this site: