Printing keys based on Hash values in Perl
16,789
Solution 1
Try with:
for my $key (keys %hash) {
print "$key\t$hash{$key}\n";
}
Solution 2
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";
}
Solution 3
print "$_\t$hash{$_}\n" for keys %hash;
Solution 4
One-liner:
map { print "$_\t$hash{$_}\n" } keys %hash;
Solution 5
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";
}
Author by
I am
Updated on August 02, 2022Comments
-
I am almost 2 years
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
-
TLP over 11 yearsYou should not use
map
as a loop statement. Use afor
loop instead. E.g.print "$_..." for keys %hash
. -
Dave Cross over 11 yearsIt's a simple fix -
print map { "$_\t$hash{$_}\n" } keys %hash;
:-) -
TLP over 11 years@DaveCross
print "$_\t$hash{$_}\n" for keys %hash
is even simpler. -
Dave Cross over 11 yearsOr even
say "$_\t$hash{$_}" for keys %hash
. But I was talking about the smallest change from what s0me0ne originally had :-)