Cody Pendant has asked for the wisdom of the Perl Monks concerning the following question:
use strict; my %hash = ( 1 => 'angel', 2 => 'buffy', 3 => 'cordelia', 4 => 'dawn', 5 => 'ethan', 6 => 'faith', 7 => 'giles' ); reorder(5,'up'); # ethan moves up: swaps place with dawn display(); sub reorder(){ my ($item,$direction) = @_; if($direction eq 'up'){ # coming soon -- 'down' my $tmp = $hash{$item}; # save ethan $hash{$item} = $hash{ ($item -1) }; # move dawn down to 5 $hash{ ($item -1) } = $tmp; # put ethan back as 4 } } sub display { print '-' x 30,"\n"; foreach my $key (sort (keys (%hash))) { printf("%12s is now number %d\n",$hash{$key},$key); } print '-' x 30,"\n"; }
Which works just fine, but then I thought, I wonder if perl can just swap the values for me and changed the reorder sub to this:
sub reorder(){ my ($item,$direction) = @_; if($direction eq 'up'){ $hash{$item,($item -1)} = $hash{ ($item -1), $item}; # maybe perl can automagically do the $tmp thing for me? } }
but when I ran it that way, I got this output:
------------------------------ angel is now number 1 buffy is now number 2 cordelia is now number 3 dawn is now number 4 ethan is now number 5 is now number 5 faith is now number 6 giles is now number 7 ------------------------------
Which doesn't make sense to me. I now have two number fives in my hash? That's not possible!
I know there's something fundamentally illogical about trying to order hashes when I could be using arrays, but leaving that aside, what happened here?
--
Every bit of code is either naturally related to the problem at hand, or else it's an accidental side effect of the fact that you happened to solve the problem using a digital computer.
M-J D
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Swapping Two Hash Values
by Zaxo (Archbishop) on May 28, 2003 at 00:35 UTC | |
by sauoq (Abbot) on May 28, 2003 at 00:53 UTC | |
|
Re: Swapping Two Hash Values
by BrowserUk (Patriarch) on May 28, 2003 at 00:51 UTC | |
|
Re: Swapping Two Hash Values
by sauoq (Abbot) on May 28, 2003 at 00:46 UTC | |
by Cody Pendant (Prior) on May 28, 2003 at 00:56 UTC | |
|
Re: Swapping Two Hash Values
by Enlil (Parson) on May 28, 2003 at 00:39 UTC | |
by Cody Pendant (Prior) on May 28, 2003 at 00:47 UTC | |
|
Re: Swapping Two Hash Values
by edoc (Chaplain) on May 28, 2003 at 00:47 UTC | |
|
Re: Swapping Two Hash Values
by halley (Prior) on May 28, 2003 at 00:30 UTC | |
by Cody Pendant (Prior) on May 28, 2003 at 00:44 UTC | |
by sauoq (Abbot) on May 28, 2003 at 00:48 UTC | |
|
Re: Swapping Two Hash Values
by Aristotle (Chancellor) on May 29, 2003 at 22:54 UTC |