Swapping Things

So we all know the COMPSCI 101 method of swapping two variables:
  $tmp = $x; $x = $y; $y = $tmp;
And we all know the better way of doing it:
  ($x, $y) = ($y, $x);

And yet, I found the following in PRODUCTION CODE, that a contractor was PAID ACTUAL DOLLARS TO WRITE:
  ($tmp_x, $tmp_y) = ($x, $y);
  ($x, $y) = ($tmp_y, $tmp_x);
Weird that they knew about parallel assignment but not that you could just apply it to two variables directly.

Anyhow, this wasn’t nearly as bad as the code I found in a different module (same vendor) to swap all the 1s and 0s in a string. Now this is a somewhat less trivial problem than simply swapping two variables, but
  $str =~ tr/01/10/;
does the job nicely. Alas, in the same vein as the variable-swap, the method that vendor went with was:
  $str =~ s/0/2/g;
  $str =~ s/1/3/g;
  $str =~ s/2/1/g;
  $str =~ s/3/0/g;

Good thing $str doesn’t contain any 2s or 3s!

3 Comments

Why don't you use the normal <pre><code class="prettyprint"> formatting of code?

Because this user’s posts are all written in (or possibly pasted into) the rich text editor, not as HTML or Markdown.

The class="prettyprint" bit is not even necessary to add, btw. That gets inserted by the syntax highlighter automatically.

Leave a comment

About morandimus

user-pic My real name is Jeremy Holland. I've been a programmer for 25 years, using primarily Perl since 2000.