Question

I realize that evaluating an array in Perl in a scalar context is useful: it results in a # of elements.

But what is the practical use of being able to evaluate a hash in a scalar context? e.g.

  • my $scalar_value = %hash;

  • scalar(%hash)

As far as I understand, it produces a string like "3/4" giving some information about the internals of the hash that appears to only be useful for debugging.

Was it helpful?

Solution

It produces a value that can be used as a TRUE/FALSE flag to know if the hash is empty (no keys).

As an example:

if (%hash) {
    print "Hash has elements\n";
} else {
    print "Hash is empty\n";
}

if forces the expression into a scalar context because of its use as a boolean expression.

It's a very similar concept to using @array in a scalar context to test for emptiness:

if (@array) {
    # NOT empty!
}

OTHER TIPS

The scalar(%hash) lets you check if the hashing algorithm is working correctly. If you have 1,000 keys and you see something like 2/16 that means all the keys are resolving to only 2 of the 16 allotted buckets. This means all your keys are very similar and causing lots of collisions, which results in long sequential searches in the bucket.

Default bucket count is 8

perl -le '$h{a}=1;print scalar %h'
1/8

Prestash the hash with 1000 buckets (to the nearest power of 2)

perl -le 'keys(%h) = 1000;$h{a}=1;print scalar %h'
1/1024

This also helps out when you bless an hash for perl OO. You can speed things up if you know there will be a lot of keys.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top