Link to home
Start Free TrialLog in
Avatar of grimjb
grimjb

asked on

simple hash question

hi,

I want to create a hash that stores multiple "values" for a given "key".

ie:
@value = (100);
$someHash{$someKey} = $value;

but then I want to add a second (and subsequent) value and maintain the previous values for the key. I am not sure of the syntax but something like:

push(@value, (542));
$someHash{$someKey} = $value;

so if I was to print $someHash{$someKey} I would get both 100 and 542.

I have tried serveral ways of doing it and I can't seem to get anything working :)

could you tell me how to set this up, the syntax for adding new values, and how I access a given element from the list of values for a particular key ?

thanks in advance
Avatar of prady_21
prady_21


This should help
push(@{$somehash}{$somevalue}),$value);

and when printing


foreach $keys ( keys %somehash) {
 printf("%s: %s\n", $keys , join(', ', @{$hash{$keys}}));
}


i am sorry , there is a mistake,
push(@{$somehash}{$somevalue}),$value);

should be
push(@{$somehash{$somevalue}},$value);
Avatar of grimjb

ASKER

I tried that but I got compliation errors on the push line. Here is what I wrote to test this method:

#!perl

%theHash=();

$value = 876;
$index = "elephant"

push(@{$theHash{$index}}, $value);
#push(@{$somehash{$somevalue}},$value);

foreach $k (keys %theHash)
{
     print $theHash{$k};
}

any ideas ?
ASKER CERTIFIED SOLUTION
Avatar of prady_21
prady_21

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The problem with ur code was that a semi colon was missing at the end of $index = "elephant"
That was the error
You also have to mention the path of perl
just do  

which perl

and you will know the directory where perl exists in your system
Avatar of grimjb

ASKER

That hit the spot :) I can't believe I missed a semi.

thanks for the help!!
Avatar of grimjb

ASKER

prady_21 was really good to put up with a perl newbie like me :) thanks again