in reply to interchanging variables the tough way

The problem with the XOR is that it produces unpredictable results when used on overlapping peices of memory. This is a much bigger problem in C, and I am pretty sure it would never happen in perl.
  • Comment on RE: interchanging variables the tough way

Replies are listed 'Best First'.
overlapping XOR swap RE: interchanging variables the tough way
by tye (Sage) on Aug 31, 2000 at 23:20 UTC
    sub xorswap { $_[0] ^= $_[1] ^= $_[0] ^= $_[1]; } $str="XORing is FUN!"; print "($str)\n"; xorswap( substr($str,0,6), substr($str,-6) ); print "($str)\n"; xorswap( substr($str,0,6), substr($str,-6) ); print "($str)\n"; xorswap( substr($str,0,9), substr($str,-9) ); print "($str)\n"; xorswap( $str, $str ); print "($str)\n"; __END__ (XORing is FUN!) (s FUN! iXORing) (XORing is FUN!) (!u'R y:u;ng is) ( )

    Note that the last case is the real reason I think you shouldn't do XOR swapping. After all, it would break Adam's Fisher-Yates Shuffle improvement. ;->

    P.S. I really only posted because I hadn't seen anyone code xorswap the "proper" way. (:

            - tye (but my friends call me "Tye")
      Well yes Tye, you can't XOR something with it-self and expect anything other then 0. That would be illogical. But it is a good point about the Fisher-Yates Shuffle, if you are using XOR to swap to locations you must be careful that the locations aren't the same... which is probably why the original algorithm does the test.