On Jul 25, Connie Chan said:

>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

Perl allows you to do

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

>$x ^= $y ; $y ^= $x ; $x ^= $y; # Swapped
>
>It works !! but how that works ?

Because of the way XOR works.  A XOR (A XOR B) = B

Here's a less tricky example:

  $x = 10;
  $y = 13;

  $x = $x + $y;  # 10 + 13 = 23
  $y = $x - $y;  # 23 - 13 = 10
  $x = $x - $y;  # 23 - 10 = 13

And then with XOR:

  $x = 10;  # 1010
  $y = 13;  # 1101

  $x = $x ^ $y;  # 1010 ^ 1101 = 0111
  $y = $x ^ $y;  # 1101 ^ 0111 = 1010
  $x = $x ^ $y;  # 0111 ^ 1010 = 1101

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


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

Reply via email to