> -----Original Message----- > From: John W. Krahn [mailto:[EMAIL PROTECTED]] > Sent: Wednesday, July 24, 2002 4:30 PM > To: [EMAIL PROTECTED] > Subject: Re: That seems interesting ? but I don't know why ? > > > Bob Showalter wrote: > > > > 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 > > Actually in perl it works with strings as well. :-) > > $ perl -le' > $x = "abcde"; $y = "fgh"; > print "\$x = $x \$y = $y"; > $x ^= $y; > $y ^= $x; > $x ^= $y; > print "\$x = $x \$y = $y"; > ' > $x = abcde $y = fgh > $x = fgh $y = abcde
Neat-o! I had to look that one up, under perldoc perlop, "Bitwise String Operators". Great for vector operations. But there's a lurking danger when applied to general-purpose swapping. Consider: $ perl -le' $x = "abcde"; $y = 123; print "\$x = $x \$y = $y"; $x ^= $y; $y ^= $x; $x ^= $y; print "\$x = $x \$y = $y"; ' $x = abcde $y = 123 $x = 123 $y = 0 <<--- Oops! What happened to "abcde"? And yet, setting $y = "123" works. Also, if either is undef, the result becomes "" or 0, depending on the other value. ($x, $y) = ($y, $x) remains the "foolproof" solution, I think... -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]