Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

help needed in retrieving the hash key

by singam (Initiate)
on Apr 05, 2006 at 09:43 UTC ( #541317=perlquestion: print w/replies, xml ) Need Help??

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

hai monks,
Is there any efficient way or algorithm to retrive the key from the hash based on the values.
both the keys and the values are unique.

Replies are listed 'Best First'.
Re: help needed in retrieving the hash key
by murugu (Curate) on Apr 05, 2006 at 09:51 UTC

    As you mentioned that keys and values are unique,

    my %hash2 = reverse %hash1;

    Now the keys and values got interchanged.

    Murugesan Kandasamy
    use perl for(;;);

Re: help needed in retrieving the hash key
by tirwhan (Abbot) on Apr 05, 2006 at 09:52 UTC
    %reverse_hash = reverse %original_hash

    For more, see perldoc -q "hash element by value"</p>

    All dogma is stupid.
Re: help needed in retrieving the hash key
by inman (Curate) on Apr 05, 2006 at 11:38 UTC
    An alternative method uses the each and keys functions to iterate over a hash and locate the keys. This has the advantage of coping with the more general case wher multiple instances of a value in addition to not requiring the storage of another hash.
    my @keys = qw ( a b c d e f g h i j); my @vals = qw ( 1 1 1 4 5 6 7 8 9 0); my %hash; @hash{@keys} = @vals; my @ones = grep {(each %hash)[1] == 1} keys %hash; print "@ones\n";

    Inverting the hash as shown previously is a better method if you are OK with the storage overhead and you will be doing multiple retrievals.

Re: help needed in retrieving the hash key
by jwkrahn (Monsignor) on Apr 05, 2006 at 13:38 UTC
    $ perl -le' my %x = qw/ one two three four five six seven eight /; print ${ { reverse %x } }{ six }; ' five

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://541317]
Approved by Samy_rio
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2019-06-17 04:53 GMT
Find Nodes?
    Voting Booth?
    Is there a future for codeless software?

    Results (76 votes). Check out past polls.

    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!