Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Returning value or key from a hash

by Corion (Patriarch)
on Apr 07, 2006 at 12:28 UTC ( [id://541852]=note: print w/replies, xml ) Need Help??


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!!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2025-06-14 11:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.