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
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
i am sorry , there is a mistake,
push(@{$somehash}{$someval ue}),$valu e);
should be
push(@{$somehash{$somevalu e}},$value );
push(@{$somehash}{$someval
should be
push(@{$somehash{$somevalu
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{$someval ue}},$valu e);
foreach $k (keys %theHash)
{
print $theHash{$k};
}
any ideas ?
#!perl
%theHash=();
$value = 876;
$index = "elephant"
push(@{$theHash{$index}}, $value);
#push(@{$somehash{$someval
foreach $k (keys %theHash)
{
print $theHash{$k};
}
any ideas ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
The problem with ur code was that a semi colon was missing at the end of $index = "elephant"
That was the error
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
just do
which perl
and you will know the directory where perl exists in your system
ASKER
That hit the spot :) I can't believe I missed a semi.
thanks for the help!!
thanks for the help!!
ASKER
prady_21 was really good to put up with a perl newbie like me :) thanks again
This should help
push(@{$somehash}{$someval
and when printing
foreach $keys ( keys %somehash) {
printf("%s: %s\n", $keys , join(', ', @{$hash{$keys}}));
}