hash key and value

A

a

Hi,
I have two hashes with the same set of keys but referring to 2 different
value sets.
I need to do the following:
foreach $key (@keys){
%hash1($key) / %hash2($key)
}
Is there any way to extract the value from the hash by the specified key?
Thanks
 
P

perlistpaul

You mean that you want to divid all the number in %hash1 with %hash2

my @results
foreach my $k(@keys) # foreach my $k(keys %hash1)
{
my $x=$hash1{$k}/$hash2{$k};
push(@results,$x);
}
 
T

Ted Zlatanov

I have two hashes with the same set of keys but referring to 2 different
value sets.
I need to do the following:
foreach $key (@keys){
%hash1($key) / %hash2($key)
}
Is there any way to extract the value from the hash by the specified key?

You need to use {} instead of () to tell Perl to give you the value in
the hash for that key (I won't repeat the correct answer given in
another followup).

Regarding your data structures, it's usually more effective to keep
the data in one multi-level hash (hash of hashes, or HoH):

my %data = (
key1 => { subkey1 => data11, subkey2 => data12 },
key2 => { subkey1 => data21, subkey2 => data22 },
....
);

instead of keeping two hashes with identical keys.

In your particular example, perhaps this would work

my %data = (
key1 => { number => 5, divisor => 3 },
key2 => { number => 8, divisor => 2 },
....
);

Then you can access the data like this

foreach my $key (keys %data) # note "my $key" and how we don't need
# @keys anymore
{
# don't divide by zero - you could do something other than dying here
die "Illegal zero divisor for key $key" unless $data{$key}->{divisor};

my $result = $data{$key}->{number} / $data{$key}->{divisor};
}

Ted
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,060
Latest member
BuyKetozenseACV

Latest Threads

Top