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