chaitu
chaitu

Reputation: 1206

how to search a hash using the values and return the corresponding key upon success in perl

I am looking for search implementation on hash using perl. I have following data in my hash

%hash = {0 => "Hello", 1=> "world"}. 

Now i want to search the hash using the values (means world and hello) and return corresponding key.

Example: I want to search for world and the result should be 1

Upvotes: 2

Views: 4129

Answers (3)

Josh Y.
Josh Y.

Reputation: 876

If:

  1. The hash isn't very large, and
  2. The values are unique

You can simply create a lookup hash with reverse:

my %lookup = reverse %hash;
my $key = $lookup{'world'}; # key from %hash or undef

Upvotes: 2

zellio
zellio

Reputation: 32484

Iterate of the keys of the hash with a for ( keys %hash ) ... statement and check the values as you go. If you find what you are looking for, return

my $hash = { 0 => "World", 1 => "Hello" };

for ( keys %$hash ) {
    my $val = $hash->{$_};
    return $_ if $val eq 'World'; # or whatever you are looking for
}

another option would be to use while ( ... each ... )

my $hash = { 0 => "World", 1 => "Hello" };

while (($key, $val) = each %$hash) {
    return $key if $val eq 'World'; # or whatever you are looking for
}

the use of { } literal creates a hash reference and not a hash

$h = { a => 'b', c => 'd' };

to create a literal hash you use ( )

%h = ( a => 'b', c => 'd' );

execution of while ... each on hashref

$h = { a => 'b', c => 'd' };
print "$k :: $v\n" while (($k, $v) = each %$h );  

c :: d
a :: b

Upvotes: 3

user966588
user966588

Reputation:

use strict;
use warnings;

my %hash = (0 => "Hello", 1=> "world");
my $val = 'world';

my @keys = grep { $hash{$_} eq $val } keys %hash;

print "Keys: ", join(", ", @keys), "\n";

This will return all keys i.e. If the value is same for multiple keys.

Upvotes: 0

Related Questions