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

Hi Brethren,

How do you return to an array either the keys or values from a hash when you have the opposite number also held in an array so that they are in the same order?

Greatful thanks as always

Replies are listed 'Best First'.
Re: Returning value or key from a hash
by Corion (Patriarch) on Apr 07, 2006 at 12:28 UTC
    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.

      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.

      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 :)