twaddlac has asked for the wisdom of the Perl Monks concerning the following question:

Hello, Monks!

I have a simple question: how can I obtain a key value a hash if I have the value (which I know is stored in the hash). Let me know if you have any ideas!! Thank you very much!

Replies are listed 'Best First'.
Re: Obtain Key from Hash using value
by kennethk (Abbot) on Jul 06, 2010 at 16:23 UTC
Re: Obtain Key from Hash using value
by BrowserUk (Patriarch) on Jul 06, 2010 at 16:24 UTC

    Which key do you want if two or more keys have the same value associated?

Re: Obtain Key from Hash using value
by jethro (Monsignor) on Jul 06, 2010 at 16:27 UTC
    You could create a second hash with keys and values switched (i.e. keys of the new hash would be the values of the original hash). If this is not possible or practical you have to check every single entry in the hash

Re: Obtain Key from Hash using value
by roboticus (Chancellor) on Jul 06, 2010 at 16:37 UTC

    twaddle:

    Freqently-asked question ...

    my %hash = ( a=>1, b=>2, c=>3 ); my $val = 2; my @keys = grep { $hash{$_}==$val } keys %hash; print "Keys: ", join(", ", @keys), "\n";

    ...roboticus

Re: Obtain Key from Hash using value
by ikegami (Patriarch) on Jul 06, 2010 at 17:43 UTC

    This begs the question as to whether your data structure is appropriate. Perhaps your keys and values are backwards? Perhaps you have two sets of keys, and should therefore have two hashes?

    my $person = { id1 => $id1, id2 => $id2, name => $name }; $persons_by_id1{$id1} = $person; $persons_by_id2{$id2} = $person; ... my $id2 = $persons_by_id1{$id1}{id2};

      If you need this you'd better use a database already. For example DBD::SQLite if you do not want to or can't install a database engine.

      Jenda
      Enoch was right!
      Enjoy the last years of Rome.

Re: Obtain Key from Hash using value
by zek152 (Pilgrim) on Jul 06, 2010 at 16:33 UTC

    I would loop through the keys and put a conditional to check to see if the value for that key is what you want.

    #assume that %hash has been defined #assume that $value_to_find has been defined foreach my $key (keys %hash) { #use == instead of eq if numeric value if ($hash{$key} eq $value_to_find) { #$key is the key you were looking for print "$key has the value: $value_to_find\n"; } }