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).
In Perl, why does concatenating a hash with a string give a fraction-looking result?
-
29-06-2022 - |
Question
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!
Solution
OTHER TIPS
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.
Example
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.