help needed in retrieving the hash key
singam
created: 2006-04-05 05:43:05
hai monks,
Is there any efficient way or algorithm to retrive the key from the hash based on the values.
Re: help needed in retrieving the hash key
created: 2006-04-05 05:51:57
Hi,

As you mentioned that keys and values are unique,

my %hash2 = reverse %hash1;

Now the keys and values got interchanged.

Regards,
Murugesan Kandasamy
use perl for(;;);

Re: help needed in retrieving the hash key
created: 2006-04-05 05:52:01
%reverse_hash = reverse %original_hash

For more, see perldoc -q "hash element by value"


All dogma is stupid.
Re: help needed in retrieving the hash key
created: 2006-04-05 07:38:50
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
created: 2006-04-05 09:38:17
$ perl -le'
my %x = qw/ one two three four five six seven eight /;
print ${ { reverse %x } }{ six };
'
five

perlmonks.org content © perlmonks.org and inman, jwkrahn, murugu, singam, tirwhan

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03