Consider the following snippet:
use strict;
use warnings;
my %a = ( a => 1,
b => 2,
c => 'cucu',
d => undef,
r => 1,
br => 2,
cr => 'cucu',
dr => '321312321',
);
my $c = %a;
print $c;
The result of this is 5/8 and I don’t understand what this represents. I read somewhere that a number from this fraction looking result might represent the number of buckets from the hash, but clearly this is not the case.
Does anyone knows how a perl hash is evaluated in scalar context?
Edit
I added a few other hashes to print:
use strict;
use warnings;
use 5.010;
my %a = ( a => 1,
b => 2,
c => 'cucu',
d => undef,
r => 1,
br => 2,
cr => 'cucu',
dr => '321312321',
);
my $c = %a;
say $c; # 5/8
%a = ( a => 1,
b => 21,
c => 'cucu',
br => 2,
cr => 'cucu',
dr => '321312321',
);
$c = %a;
say $c; # 4/8
%a = ( a => 1,
b => 2,
c => 'cucu',
d => undef,
r => 1,
br => 2,
cr => 'cucu',
dr => '321312321',
drr => '32131232122',
);
$c = %a;
say $c; #6/8
So, you call a ‘tuple’ like a => 1 a bucket in the hash? in that case, why is the last hash still having 8 as a denominator when it has 9 ‘tuples’ ?
Thank you all for your responses until now 🙂
[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.