Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: multiple values for one key in hash

by wade (Pilgrim)
on May 12, 2008 at 22:04 UTC ( [id://686157]=note: print w/replies, xml ) Need Help??


in reply to multiple values for one key in hash

How about using a reference to an array. Here's a little ditty that builds the kind of hash for which you're looking and then prints out the results:

use strict; use warnings; use diagnostics; use Data::Dumper; my %hash; my $key; my $value; my @data = ("foo",1, "bar",2, "foo",3, "baz",4); while ($key = shift (@data)) { $value = shift (@data); # push the value on the array push @{$hash{$key}}, $value; } print Dumper \%hash;

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

Update: apparently you can just push the value.

--
Wade

Replies are listed 'Best First'.
Re^2: multiple values for one key in hash
by moritz (Cardinal) on May 12, 2008 at 22:12 UTC
    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.

      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?

Log In?
Username:
Password:

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

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

    No recent polls found