in reply to Re: Perl Internals: Hashes
in thread Perl Internals: Hashes
To expound on demerphq's response with an example:
Given a hash, like so:
When you call a subroutine with an array or hash, it gets flattened into a list. For a hash, that means giving all of its keys and corresponding values. So this:my %test; $test{a} = 1; $test{b} = 2;
is the same as this:something(%test);
(Note that when hashes are flattened, the keys may come out in any order, so it could have also been something(b, 2, a, 1);.)something(a, 1, b, 2);
The other side of this situation is that you can fill a hash directly with a list, instead of doing each key one-at-a-time. When you assign to a hash with a list, each odd item becomes a key, and the corresponding even item is its value. So we could have filled the hash like this:
and it would be exactly the same. Note that this is also the same as the more familiar:%test = (a, 1, b, 2);
as the => is just a type of comma that auto-quotes its left side operand. Now you can see what happens:%test = (a => 1, b => 2);
And inside the sub:something(%test); # is like something(a, 1, b, 2);
And so it turns out that you're just doing a basic copy. The hash inside the sub will be a copy of the one you passed in.my %hash = @_; # is like %hash = (a, 1, b, 2);
In Section
Seekers of Perl Wisdom