in reply to getting the number of hashes
I suspect they may be asking for the number of hash elements in a particular hash. If so, perlfaq4 comes to the rescue:
How can I know how many entries are in a hash?
If you mean how many keys, then all you have to do is take the scalar sense of the keys() function:
$num_keys = scalar keys %hash;In void context, the keys() function just resets the iterator, which is faster for tied hashes than would be iterating through the whole hash, one key-value pair at a time.
In other words, it's better to use the above than to use something like these:
$number = grep(//, keys %hash); for (keys %hash) { $number++; }
However, grep is a good solution if you want something more specific, for example:
## Find the number of elements that are defined: $number = grep(defined $hash{$_}, keys %hash); ## Find the number of elements that are "true": $number = grep($_, values %hash); ## Find the number of elements where the key equals the value: $number = grep($_ eq $hash{$_}, keys %hash);
|
|---|