I am writing this, because of something I read in Programming Perl. It went something like this: Other languages force you to use a temporary variable to swap variables, but perl doesn't. In perl you can do this: ($a,$b)=($b,$a). I just want you to know, I love the O`Reily series of books, this is not an attack against them, that said, I'll move on.
Now, I'm not exactly sure, but I remember reading somewhere that perl makes an internal copy of the variables to swap. So, that solution is really just ducking the bullet. If you really don't want to use a temporary variable, as in this code:
UPDATE: Thanks Rich, I should have changed that last asignment to $b = $temp. Sorry.$temp = $a; $a = $b; $b = $a;
You can use a little ingenuity. Now I have never seen any of these following things in a book, nor have I been taught them in a class (I'm only 15, I can't really take many cs classes), so I don't know how widespread this knowledge is. First of all, I don't really recomend you use all of these solutions (only the first is better than using a temporary variable), but it's nice to understand the concepts.
First, if you want to swap integers, use this:
I benchmarked this, and it performed exactly the same as the temperary solution, but it does not waste a variable. (Those monks who wish to see how this works, just click the readmore at the bottom of this post). If you wish to switch strings without a temporary variable, just use this code:$a ^= $b; $b ^= $a; $a ^= $b;
When I benchmarked this, the temporary variable solution was very slightly faster. Finally, if your variables could be integers, but could also be floating point numbers, you can use this solution:$a .= $b; $b = substr($a,0,length($a)-length($b)); substr($a,0,length($b)) = '';
Now, I know it's easier to just use ($a,$b)=($b,$a), but I wrote this because I was concerned with the language, the book said that other languages force you to use a temporary variable, well they don't. Also, I was recently involved in a robotics competition, in which we used the PBASIC programming language with the BASIC 2SX chip. We had a limited supply of variables, so we had to use solutions like these all the time. So, I'm quite familiar with little optimiztions like this one.$a += $b; $b = $a - $b; $a -= $b;
It works by creating a mask of $a and $b, and storing it in $a. This mask, when given the original value of $a, returns $b, and vice versa. Next we store in $b, the value of the mask XORed to $b, returning $a, just what we want. Next, we store in $a the value of the mask XORed to $b, which is now the original value of $a, so it returns $b, and the variables are swapped.$a ^= $b; $b ^= $a; $a ^= $b;
The other examples are relatively easy to follow, so I will leave them out of this post.
In reply to Temporary Variables by srawls
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |