fexam fexam - 5 months ago 17
Perl Question

Exchange hash values without temporary variable

I have two hash values a couple of levels deep in a data structure that I would like to exchange and then switch back later.

$hashref->{$irrelevant}{$key1}
and
$hashref->{$irrelevant}{$key2}


Since they are such long names,
($a, $b) = ($b, $a)
would be way too long for a single line of code.

Is there a way to do this elegantly, or am I stuck taking up three lines by exchanging with a temporary variable?

Answer

You people who hide "irrelevant" data meanings aren't doing anyone any favours. We still have to write a solution, but it has to be in abstract terms that make no sense either to you or me!

The neatest way I can think of is with a pair of hash slices

my $irrelevant_href = $hashref->{$irrelevant};

@{$irrelevant_href}{$key1, $key2} = @{$irrelevant_href}{$key2, $key1};