Reputation: 1067
I need to print keys based on vales in hash. Here is the code, I wrote
foreach $value (values %hash)
{
print "$value\t$hash{$value}\n";
}
Error: I can only print values, but not keys.
Any help will be greatly appreciated.
Thanks
Upvotes: 3
Views: 17455
Reputation: 468
The title requests to print key based on the value.
if your key and value in your harsh table should be one to one
foreach $key (keys %hash)
{
$r_hash{$hash{$key}}=$key;
}
....
Upvotes: 1
Reputation: 16223
Try with:
for my $key (keys %hash) {
print "$key\t$hash{$key}\n";
}
Upvotes: 4
Reputation: 1482
if you want to access it by values, then define your hash as
$x = { 'x1' => [ 'one','x1']}
foreach ( values %$x )
{
foreach $m1 (@$_) {
print "$m1\n";
}
}
Notice you can get the key from value by second member of the value array.
Upvotes: 0
Reputation: 677
I would probably use while and each if you want to iterate through keys and values:
while (my ($key, $value) = each %hash) {
say "$key -> $value";
}
Upvotes: 1
Reputation: 944442
Hashes are designed to be accessed by key, not by value. You need to loop over a list of keys, not values.
Then you can use the keys to access the associated values.
foreach my $key (keys %hash) {
my $value = $hash{$key};
say "$key = \t$value";
}
Upvotes: 8