fexam fexam - 1 year ago 72
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.


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 Source

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};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download