What do you get if you evaluate a hash in scalar context?

[The OP is asking about the format of the string returned by a hash in scalar context before Perl 5.26. Since Perl 5.26, a hash in scalar context no longer returns a string in this format, returning the number of elements in the hash instead. If you need the value discussed here, you can use Hash::Util‘s bucket_ratio().]

A hash is an array of linked lists. A hashing function converts the key into a number which is used as the index of the array element (“bucket”) into which to store the value. The linked list handles the case where more than one key hashes to the same index (“collision”).

The denominator of the fraction is the total number of buckets.

The numerator of the fraction is the number of buckets which has one or more elements.

For hashes with the same number of elements, the higher the number, the better. The one that returns 6/8 has fewer collisions than the one that returns 4/8.

Leave a Comment