> -----Original Message-----
> From: Connie Chan [mailto:[EMAIL PROTECTED]]
> Sent: Wednesday, July 24, 2002 12:08 PM
> To: [EMAIL PROTECTED]
> Subject: That seems interesting ? but I don't know why ?
> 
> 
> In normal case, when we want to swap 2 var, 
> , say $x and $y, we do in this way :
> 
> $z = $x; $x = $y; $y = $z;  # Swapped

Nah, that's the C way. See below...

> 
> today, I suddenly found a code like this :
> 
> $x ^= $y ; $y ^= $x ; $x ^= $y; # Swapped
> 
> It works !! but how that works ?
> Could anybody tell me ?

Well, it only works for integers. It's because of the way ^ 
(bitwise xor) works. Given x=0 and y=1, for instance:

   x = x ^ y    y = y ^ x   x = x ^ y
   x = 0 ^ 1    y = 1 ^ 1   x = 1 ^ 0
   x = 1        y = 0       x = 1

So, now x=1 and y=0. You can prove this for any combination of 
x and y in the range 0..1 (1 bit). The ^ performs the operation 
on each bit of a larger integer.

But the "Perl way" to swap any given $x and $y is:

   ($x, $y) = ($y, $x);

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to