Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^3: Printing keys from a hash by value?

by aaron_baugher (Deacon)
on Jan 30, 2012 at 20:28 UTC ( #950836=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Printing keys from a hash by value?
in thread Printing keys from a hash by value?

It's not different, but that's not what he did. First he passed his hash, which presumably had words as keys and numbers as values, to reverse, which happily treated it as a list and reversed the list, which he assigned to another hash, turning the reversed list back into a hash. For example:

my %hash = ('one' => 1, 'two' => 2, 'three' => 3, 'four-minus-one' => +3); my %newhash = reverse %hash; # %newhash now contains (1 => 'one', 2 => 'two', 3 => 'four-minus-one' +) # or # (1 => 'one', 2 => 'two', 3 => 'three')

See, it turned the original hash into a list and reversed it. Since the last item in the list was a value, that became the first item in the reversed list, becoming a key, with the next-to-last item in the original list (that value's key) becoming its value, and so on. And if any value appeared twice in the original list, it can't appear more than once as a key in the new hash, so all but one of its matching keys will be clobbered. Also, you can't know which key/value pairs will get clobbered, since a hash is unordered by definition.

Aaron B.
My Woefully Neglected Blog, where I occasionally mention Perl.


Comment on Re^3: Printing keys from a hash by value?
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (15)
As of 2014-07-11 16:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (232 votes), past polls