[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [Fun With Perl] Re: How to swap $p and $q without $tmp





On 13 Jun 99, at 22:43, Bek Oberin wrote:

> Roland Giersig wrote:
> > Easy. Just right to left. Equivalent multiline version:
> >  $q ^= $p;
> >  $p ^= $q;
> >  $q ^= $p;
> 
> I must be dumb.   I still don't get it.  Maybe its just too
> late at night?

It is the hll equivalent of an old assembly-language programmer's trick 
(I used to really use it in the dark ages to exchange values, toggle bits 
in the middle of a word, etc.  As a real-world practical use, this very 
technique [but in assembler, of course] was used to interchange the 
source and destination addresses in ARPAnet packets to send back 
acknowledges... or does it disqualify something for mention on this list 
for it to have been used for something useful? :o)).  For a long time it 
was one of my favorite programming hacks...

If you do the above explicitly, it is easier to see:

$q = $q XOR $p.

$p = $p XOR ($q XOR $p) = $p XOR ($p XOR $q) = ($p XOR $p) XOR $q = $q

and so now $p = $q

$q = ($q XOR $p) XOR $q  [and as above] = $p

  /Bernie\
-- 
Bernie Cosell                     Fantasy Farm Fibers
mailto:bernie@fantasyfarm.com     Pearisburg, VA
    -->  Too many people, too few sheep  <--          

==== Want to unsubscribe from this list? (Don't you love us anymore?)
==== Well, if you insist... Send mail with body "unsubscribe" to
==== fwp-request@technofile.org