Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Question about fast switch hash key-value pairs.

by lihao (Monk)
on Apr 02, 2008 at 21:25 UTC ( [id://678047]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, monks

Without loading any Perl modules, what is the fastest or best way to change key=>value pairs to value=>key pairs of a large hash. Assume no duplication in both key and value fields.. Many thanks

BTW. I am now using the following which looks dummy

$hash1{$hash2{$_}} = $_ for keys %hash2;

lihao

Replies are listed 'Best First'.
Re: Question about fast switch hash key-value pairs.
by ikegami (Patriarch) on Apr 02, 2008 at 22:48 UTC

    Your code is fine.

    Another way is to use a hash slice, using values to get the keys and keys to get the values.

    Yet another way is to assign one hash to the other while using reverse.

    All of these methods assumes the values are unique.

    Update: Added last solution.

      All of these methods assumes the values are unique.

      You might want to add an if exists check in case the values are not unique, and perhaps add the duplicate values to an anonymous inner array (see HASHES OF ARRAYS).

      Software speaks in tongues of man.
      Stop saying 'script'. Stop saying 'line-noise'.
      We have nothing to lose but our metaphors.

Re: Question about fast switch hash key-value pairs.
by FunkyMonk (Chancellor) on Apr 02, 2008 at 21:32 UTC
    Homework?

    Did you check the FAQ?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-03-29 07:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found