in reply to Re: Re: swapping vars, two ways, 2 results...
in thread swapping vars, two ways, 2 results...

XOR swapping of strings in perl is BAD. I think it's merlyn who refers to these things as bad memes?

The reason is that if the strings are different lengths, you get subtly "broken" results...

my ($a,$b)=("a","bb"); printf("/%s/ (%d bytes) /%s/ (%d bytes)\n",$a,length($a),$b,length($b) +); $a^=$b^=$a^=$b; printf("/%s/ (%d bytes) /%s/ (%d bytes)\n",$a,length($a),$b,length($b) +);'
This results in:
/a/ (1 bytes) /bb/ (2 bytes) /bb/ (2 bytes) /a/ (2 bytes)
The unexpected "2 bytes" for /a/ occurs because the string is still 2 characters long, but the 2nd character is now null.

This can (and will) trip you up later, because $b ne "a", even though they print the same.
--
Mike

Replies are listed 'Best First'.
Re: Re: Re: Re: swapping vars, two ways, 2 results...
by BrowserUk (Patriarch) on Dec 19, 2002 at 19:41 UTC

    Your right of course. Its not good at all with different length strings.


    Examine what is said, not who speaks.