What is the most elegant way to turn a hash inside out?
By that I mean replace keys with values and vice versa (assuming that all the values are 100% unique).
E.g.
Start with
my %start = (1=>"a", 2=>"b", 3=>"c");
# ...
# PROFIT:
my %finish = ("c" => 3, "b" => 2, "a" => 1);
I know I can do it the brute force way:
foreach my $key (keys %start) {
my $value = $start{$key};
$finish{ $value } = $key;
}
But this can’t be the most Perly-elegant way of doing so!
reverseis probably among the most idiomatic ways:This works, because reverse takes the
%starthash as a list of the form (key1 value1 key2 value2… keyN valueN); then reverse reverses the list (valueN keyN … value1 key1). Assigning that list to a hash variable then turns it into a hash with odd elements becoming keys and even elements becoming valuesOr you can use
map(less elegant but still idiomatic):