I have the following hash:
my %villains = {
"Boba" => "Fett",
"Darth" => "Vader",
"Moff" => "Tarkin",
}
I then print it like so:
print "".%villains;
I get the following output:
1/8
What semantics in Perl make this happen?
Thank you!
You are evaluating the hash in scalar context. When you do this it actually returns a fraction of the number of buckets touched over the total number of buckets, unless the hash has not been used in which case it evaluates to false. See this perldoc for more info (near the end of the section).
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. This is pretty much useful only to find out whether Perl's internal hashing algorithm is performing poorly on your data set.
This could use some explaining for anyone unfamiliar with hash internals: When items are added to a hash, they're arranged into buckets based on a hashing algorithm so they can be retrieved more efficiently.
You're collecting toy cars. In order to find your cars easily you've decided to put them in different buckets based on colour. You have buckets for Red, Yellow, Green, Blue and Black coloured cars.
You add a new Green Ford Mustang to your collection so it goes in the Green bucket. Next time you want to find this car, you can go directly to the Green bucket and have a smaller selection to search through.
In this example the car collection is a hash
, each car is a hash entry
and colour is the hashing algorithm
. As the collection also contains red, blue and black cars they are arranged fairly efficiently, using 4/5
of the buckets.
However, if you were to use this system for a collection of red cars, the hashing algorithm would be very inefficient. It would only use 1/5
of the buckets and finding a particular car would involve searching through the entire collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With