in reply to Invert a hash... not a FAQ (I hope)
I don't think you can get much faster than this in pure Perl.sub invert { my $x = shift; my $y = {}; while (my ($key1, $value1) = each %$x) { while (my ($key2, $value2) = each %$value1) { $y->{$key2}{$key1} = $value2; } } return $y; }
If you want to speed this up, save memory, etc, then you have to look into why you find the need to invert multi-level hashes regularly. Since you haven't shown an example of a design problem where you find yourself wanting to do that, I can't comment on whether your design is appropriate or whether there is an alternate way to tackle those problems that would work better.
In short I can think of some situations where inverting a hash is absolutely the right thing to do. I can think of others where there is no real need to do it. Without more context, there is no point in my guessing which applies to you.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Invert a hash... not a FAQ (I hope)
by djacobow (Initiate) on Jan 22, 2009 at 01:37 UTC | |
by tilly (Archbishop) on Jan 22, 2009 at 01:43 UTC | |
by djacobow (Initiate) on Jan 22, 2009 at 02:01 UTC | |
by tilly (Archbishop) on Jan 22, 2009 at 02:24 UTC | |
by Jenda (Abbot) on Jan 22, 2009 at 02:22 UTC | |
by jhourcle (Prior) on Jan 22, 2009 at 15:10 UTC | |
by kyle (Abbot) on Jan 22, 2009 at 01:59 UTC |