Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^2: multiple values for one key in hash

by moritz (Cardinal)
on May 12, 2008 at 22:12 UTC ( [id://686160]=note: print w/replies, xml ) Need Help??


in reply to Re: multiple values for one key in hash
in thread multiple values for one key in hash

Note: you have to create the anonymous reference -- you can't just push a value if the key doesn't exist.

In perl you can ;-)

use strict; use warnings; use Data::Dumper; my %hash; push @{$hash{key}}, 'value'; print Dumper \%hash; __END__ $VAR1 = { 'key' => [ 'value' ] };

This nice feature is called "autovivification" and is quite useful most of the time.

Replies are listed 'Best First'.
Re^3: multiple values for one key in hash
by wade (Pilgrim) on May 12, 2008 at 22:46 UTC

    Son of a gun! You can just push the value. I could have sworn that this didn't work when I tried it at my old job (about 2 years ago). Is this a feature that has happened since then or have I been brain dead all this time?

    Thanks, moritz; ++

    --
    Wade
      It doesn't work if there was an undef explicitly assigned to the value before. A lot of people get tripped up by this because they just assign undef to something they don't use anymore instead of deleting the key.

      My criteria for good software:
      1. Does it work?
      2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

        How would autovivification know that the undef in lvalue context it's autovivifying wasn't the original undef?

        $ perl -MYAML::Syck -le '$h{bar}=1;$h{bar}=undef;push @{$h{bar}}, qw/a + b c/;print Dump( \%h )' --- bar: - a - b - c

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-20 03:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found