in reply to Exchanging Variables

One way to swap two variables with no temporaries that isn't specific to perl is:

$a = $a ^ $b; $b = $a ^ $b; $a = $a ^ $b;


Update: The '^' operator is called "exclusive or" or XOR. It returns the bitwise XOR of the operands. XOR is equivalent to bitwise addition mod 2.

Replies are listed 'Best First'.
Re (tilly) 2: Exchanging Variables
by tilly (Archbishop) on Aug 10, 2001 at 02:37 UTC
    First of all $a and $b are special in Perl so it is a good idea to avoid using them, even for throw-away variables.

    That aside, this method of swapping data is unreliable. Witness:

    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";
    What happened, of course, is that you stringified the object and so lost the reference.

    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]; }
Re: Re: Exchanging Variables
by Mr.T (Sexton) on Aug 10, 2001 at 01:41 UTC
    I think I understand, but I am not exactly sure what the '^' operator does. Please forgive my ignorance, but what does it do, and what is it called? (In Perl.)

    Mr.T
    qw/"I pity da foo' who don't use Perl!"/;