in reply to Return value given a key

You title suggest you have a key, and want a value, but your question is actually the other way around.

The answer is that if you want to find a key belonging to a certain value, you should have used a different datastructure. In a hash, keys are unique, values don't have to. The entire point of a hash is to be able to search with keys - if you want to search with the values, you should have used the values as the keys, and the keys as the values.

Perl --((8:>*

Replies are listed 'Best First'.
Re^2: Return value given a key
by monarch (Priest) on Nov 22, 2005 at 13:01 UTC
    Or, if you want to speed up looking for a value, build an inverse hash..
    my %forwardhash = ( key1 => 'value1', key2 => 'value2', key3 => 'value3' ); my %reversehash = (); while ( my ( $key, $value ) = each %forwardhash ) { $reversehash{$value} = $key; } use Data::Dumper; print Dumper( \%reversehash );

    Outputs:

    $VAR1 = { 'value1' => 'key1', 'value2' => 'key2', 'value3' => 'key3' };