What do you get if you evaluate a hash in scalar context?
The behaviour has changed since Perl 5.25. See perldata for Perl 5.26:
Prior to Perl 5.25 the value returned was a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash. This is pretty much useful only to find out whether Perl's internal hashing algorithm is performing poorly on your data set. For example, you stick 10,000 things in a hash, but evaluating
%HASH
in scalar context reveals1/16
, which means only one out of sixteen buckets has been touched, and presumably contains all 10,000 of your items. This isn't supposed to happen.As of Perl 5.25 the return was changed to be the count of keys in the hash. If you need access to the old behavior you can use
Hash::Util::bucket_ratio()
instead.
[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.
From perldoc perldata
:
If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash.
In your case, you have five values (1
,2
,''cucu'
,undef
, and '321312321'
) that have been mapped to by eight keys (a
,b
,c
,d
,r
,br
,cr
, and dr
).