Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: inverting keys in a 2-D Hash

by Athanasius (Archbishop)
on Aug 30, 2015 at 13:54 UTC ( [id://1140434]=note: print w/replies, xml ) Need Help??


in reply to inverting keys in a 2-D Hash

Hello melmoth, and welcome to the Monastery!

I don’t know about the “cleanest” way, but delete works nicely:

#! perl use strict; use warnings; use Data::Dump; my %HASH; $HASH{keyA}{keyB} = [1 .. 4]; dd \%HASH; my $array_ref = $HASH{keyA}{keyB}; delete $HASH{keyB}; delete $HASH{keyA}; $HASH{keyB}{keyA} = $array_ref; dd \%HASH;

Output:

23:53 >perl 1360_SoPW.pl { keyA => { keyB => [1 .. 4] } } { keyB => { keyA => [1 .. 4] } } 23:53 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: inverting keys in a 2-D Hash
by LanX (Saint) on Aug 30, 2015 at 14:21 UTC
    Maybe you should write to a new hash if you can't be sure about the risk of losing information overwriting 2D symmetries. (Imagine keys A and B being from the same set of values, like indices of a matrix)

    Afaik should delete return the deleted value, such that you can do it in a one-liner

    Otoh no need to delete when writing a new hash.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

Re^2: inverting keys in a 2-D Hash
by Laurent_R (Canon) on Aug 30, 2015 at 15:16 UTC
    delete $HASH{keyB};
    What is the point of this code line, since $HASH{keyB} probably doesn't exist?

    Personally, I would prefer, if possible, to make a copy of the original hash.

Re^2: inverting keys in a 2-D Hash
by sundialsvc4 (Abbot) on Aug 31, 2015 at 03:16 UTC

    Can’t say that I agree with you on this one:   there’s really no compelling requirement to attempt to modify the structure “in place,” and plenty of good reasons not to . . .

    Especially when we consider that “what the hashref-of-hashrefs actually contains is ...” arrayrefs.   We aren’t copying any arrays:   what we’re actually doing is creating a second (inverted ...) hashref-of-hashrefs structure, which contains references to ... the same arrays that the “old” one refers-to.   (And we are, thereafter, entirely free to keep both of these hashrefs-of-hashrefs, without penalty, since they are both effectively just “indexes” to a single collection of anonymous-arrays.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-04-24 10:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found