in reply to Re: Exchanging Variables
in thread Exchanging Variables
That aside, this method of swapping data is unreliable. Witness:
What happened, of course, is that you stringified the object and so lost the reference.my $x = ["hello"]; my $y = ["world"]; print "We have \$x=$x and \$y=$y.\n"; print "The first element of \$x is '$x->[0]'\n"; print "The first element of \$y is '$y->[0]'\n"; print "Now swapping...\n"; $x = $x ^ $y; $y = $x ^ $y; $x = $x ^ $y; print "We have \$x=$x and \$y=$y.\n"; print "The first element of \$x is '$x->[0]'\n"; print "The first element of \$y is '$y->[0]'\n";
Now if you want a sneaky way to swap variables, the following takes a list of variables as arguments and rotates them. The first goes to the end, the rest move forward one. With 2 variables this just swaps.
my $x = ["hello"]; my $y = ["world"]; print "We have \$x=$x and \$y=$y.\n"; print "The first element of \$x is '$x->[0]'\n"; print "The first element of \$y is '$y->[0]'\n"; print "Now swapping...\n"; rotate($x, $y); print "We have \$x=$x and \$y=$y.\n"; print "The first element of \$x is '$x->[0]'\n"; print "The first element of \$y is '$y->[0]'\n"; # And here is the magic bit sub rotate { @_[0..$#_] = @_[1..$#_, 0]; } # BTW here is something that won't work. Lists are not arrays! :-) sub wont_rotate { @_ = @_[1..$#_, 0]; }
|
|---|