Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Returning value or key from a hash

by Gavin (Archbishop)
on Apr 07, 2006 at 12:24 UTC ( [id://541850]=perlquestion: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://541850]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (11)
As of 2024-04-23 08:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found