prasadbabu has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

i am new to perl

i have a doubt in a hash workings

input: %hash = ("1" => "canada", "1" => "us", "2" => "england", "3" => "france", "3" => "russia");

i need a output as

output:

1 # canada, us

2 # england

3 # france, russia

when i prints $hash{"1"} i am getting the "us" only but i need all the values of the key

is it possible to access all the values of a single key?

if so, please clarify and i need an example.

i think a key can have more than one values.

thanks in advance

Prasad

20040904 Edit by castaway: Changed title from 'hash'

Replies are listed 'Best First'.
Re: Multiple Values for a Key
by ccn (Vicar) on Sep 02, 2004 at 14:24 UTC

    You can not assign multiply values to a key, but you can use array references

    %hash = ("1" => ["canada", "us"], "2" => ["england"], "3" => ["france", "russia"]); print "$_ # ", join(", ", @{$hash{$_}}), "\n" foreach keys %hash;
Re: Multiple Values for a Key
by Limbic~Region (Chancellor) on Sep 02, 2004 at 14:28 UTC
    prasadbabu,
    You have misunderstood hashes. You should have a look at perldoc perldata. A hash can only have a single scalar as a value. The good news is that references are scalars, so you can have a reference to another data type such as an array. There are tied implementations such as Tie::Hash::MultiValue that would do this for you, but you can do it yourself too.
    #!/usr/bin/perl use strict; use warnings; my %hash; my @pairs = qw(1 canada 1 us 2 england 3 france 3 russia); while ( @pairs ) { my $key = shift @pairs; my $val = shift @pairs; push @{ $hash{$key} } , $val; } for ( sort keys %hash ) { print "$_ # ", join ', ' , @{ $hash{$_} }; print "\n"; } __END__ 1 # canada, us 2 # england 3 # france, russia

    Cheers - L~R

    Note: You would normally assign anonymous arrays to the keys as ccn shows. I did it this way to show how to add new elements after the initial hash is created a la push.
Re: Multiple Values for a Key
by hardburn (Abbot) on Sep 02, 2004 at 14:28 UTC

    Nope, you only get one value for a key. The last value assigned to that key is the one that wins ("us" in this example). To get multiple values, you'll need a Hash-of-Arrays, but before you can do that, you'll need to understand references. Read perlreftut, perlref, and perldsc.

    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

Re: Multiple Values for a Key
by perlfan (Parson) on Sep 02, 2004 at 14:35 UTC
    You could also use an array of arrays to maintain your order:
    my @countries = ([canada, us], [england], [france, russia]);

      I agree with that sentiment, if you're relating things by number, and will never need to sort by value...then array is your easiest implementation.