I am
I am

Reputation: 1067

Printing keys based on Hash values in Perl

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

Answers (7)

Leon
Leon

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

DarkAjax
DarkAjax

Reputation: 16223

Try with:

for my $key (keys %hash) {
    print "$key\t$hash{$key}\n";
}

Upvotes: 4

michael501
michael501

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

Dimitar Petrov
Dimitar Petrov

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

mmertel
mmertel

Reputation: 397

print "$_\t$hash{$_}\n" for keys %hash;

Upvotes: 4

s0me0ne
s0me0ne

Reputation: 516

One-liner:

map { print "$_\t$hash{$_}\n" } keys %hash;

Upvotes: 1

Quentin
Quentin

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

Related Questions