Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Perl Internals: Hashes

by gnork (Scribe)
on Apr 15, 2004 at 08:20 UTC ( #345332=note: print w/ replies, xml ) Need Help??

in reply to Perl Internals: Hashes

I wondered for a long time why

sub something { my %hash = @_ print $hash{1} . "\n"; } %test; $test{1} = 1; something(%test);
works like a charme. Is it some internal magic or simply that hashes and named arrays are implemented not that different?

cat /dev/world | perl -e "(/(^.*? \?) 42\!/) && (print $1))"

Comment on Re: Perl Internals: Hashes
Download Code
Re: Re: Perl Internals: Hashes
by demerphq (Chancellor) on Apr 15, 2004 at 09:17 UTC

    The parameter part of a subroutine call is normally a list. If a hash or an array gets put in one they are listified. In the case of a hash this means a list of key/value pairs. Likewise, if an array contains an even number of elements you can "pour" it into a hash and the elements will be paired off into key/value slots.


      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi

Re: Re: Perl Internals: Hashes
by kelan (Deacon) on Apr 15, 2004 at 21:09 UTC

    To expound on demerphq's response with an example:

    Given a hash, like so:

    my %test; $test{a} = 1; $test{b} = 2;
    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:
    is the same as this:
    something(a, 1, b, 2);
    (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);.)

    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:

    %test = (a, 1, b, 2);
    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:
    something(%test); # is like something(a, 1, b, 2);
    And inside the sub:
    my %hash = @_; # is like %hash = (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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://345332]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (11)
As of 2014-07-29 12:57 GMT
Find Nodes?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:

    Results (217 votes), past polls