Tuesday, July 28, 2009

What makes code Perlish?

There is a lot of discussion in lots of places about "perlish" code. What perlish code is. What it isn't. But, not a lot about how you can tell the difference.

The first metric to look for is conciseness. How many lines of code does it take to express a concept? For example, swapping a two variables. In most languages, you have to use an explicit temp variable, such as in the following C code:

temp = i;
i = j;
j = temp;

That's three lines to express a single concept. Most imperative languages require the same thing. Perl (and similar languages like Python and Ruby) does it in one.

( $i, $j ) = ( $j, $i );

Two lines doesn't sound like much. But, think about it as a 3-to-1 reduction. That means 300 lines is now 100. Ohhhh.

4 comments:

  1. I find this a spurious example, because I'm not aware of any real situations (in well written code) in which you'd want to swap variables :)

    ReplyDelete
  2. AdamKennedy, have you considered sorting algorithms?

    ReplyDelete
  3. This might not be the best example for concision because it's the lack of a temp that's the real win. That is, the Perlish code isn't better just because it's shorter; it's really better because it doesn't create another variable. We didn't just save 200 lines, we saved 100 temporary variables. Or worse, the same variable scoped globally (or, at least, wider than necessary) reused 99 more times.

    ReplyDelete
  4. Well, if all you are concerned with is the extra variable you can say

    a ^= b;
    b ^= a;
    a ^= b;

    Humorously, this even works on strings in Perl:

    #!/usr/bin/perl

    use strict;
    use warnings;

    my $x = "foo";
    my $y = "quux";

    $x ^= $y;
    $y ^= $x;
    $x ^= $y;

    print "x $x y $y\n";

    ReplyDelete