in reply to Returning value or key from a hash

use strict; use warnings; my %hash = ( foo => 'bar', 42 => 23, hello => 'world', ); my @interesting_keys = qw(foo hello); my @values = map { $hash{$_} } @interesting_keys; my @interesting_values = qw(bar 23); my %reversed_hash = reverse %hash; my @keys = map { $reversed_hash{$_} } @interesting_values;

Update: Made the code conform to strict, after tirwhan's note.

Replies are listed 'Best First'.
Re^2: Returning value or key from a hash
by tirwhan (Abbot) on Apr 07, 2006 at 12:47 UTC

    You're missing a my before the @values and @keys arrays.Update: Not any more.

    And while I'm nitpicking :-), personally I find it clearer to use a hash slice instead of map:

    @values = @hash { @interesting_keys }; @keys = @reversed_hash { @interesting_values };
    YMMV of course.

    All dogma is stupid.
Re^2: Returning value or key from a hash
by tlm (Prior) on Apr 07, 2006 at 14:18 UTC

    Reversing a hash is cool but dangerous. If the original hash has repeated values, reversing it loses information.

    the lowliest monk

      But in this case, I assume the hash is reversible, as the original post doesn't mention what to do in conflicts :)

        It worked for me just fine
        Cheers all!!