Wednesday, July 29, 2009

Perlish code part deux

Wow. Lots of good comments on my last post. (well, lots of comments by this novice's standards, at any rate.) And, while I'm pretty sure some were tongue-in-cheek, it's obvious that my rather sparse discussion of conciseness was a bit too concise. So, maybe a longer example is in order.

Most programmers (perlers or not) will easily understand the following:
my @data = (
{
id => 1,
first_name => 'Barney',
last_name => 'Rubble',
age => 33,
gender => 'male',
},
# more of the same
);

# Create a string of "first last, first last, ...", sorted by name, for just males
my $names = join ", ", map {
"$_->{first_name} $_->{last_name}"
} sort {
$a->{last_name} cmp $b->{last_name}
|| $a->{first_name} cmp $b->{first_name}
} grep {
$_->{gender} eq 'male'
} @data;

I'm not going to even attempt how to do that in C. Needless to say, I'm betting it's going to be significantly longer than 8 lines. In fact, I'm betting it'll be closer to 10x that. The Java version is likely to be 5x that and likely more if you add in the building and maintenance of the initial data structure.

That is concise Perl. It takes advantage of the native high-level data structures (hashes and arrays) and the operators built for them (sort, map, and grep) to create very easy-to-understand complex code. And, we're not even touching string manipulation, supposedly Perl's greatest strength.

5 comments:

  1. When it comes down to it, I think the string manipulation meme is false, unless you specifically mean "for writing one-liners" -- or, perhaps, "n-liners", as they often become.

    Once you get into more structured or detailed string tasks, I don't see Perl as having any great strength over its dynamic language cousins (except maybe in Unicode support, but that's not usually what people mean).

    ReplyDelete
  2. It would be easier to read if HTML didn't strip out consecutive whitespace. A pre tag or judicious use of   would help.

    ReplyDelete
  3. I am using

    code {
        font-family:"Andale Mono",Monaco,Monospace;
    }
    pre {
        font-family:"Andale Mono",Monaco,Monospace;
    }

    in the Layout->Edit HTML->Edit Template section. I also have

    em {
        font-style: normal;
        font-family:"Andale Mono",Monaco,Monospace;
    } /* steal em to mean code for the comments */

    to get around blogger stripping code and pre from comments.

    ReplyDelete
  4. Chas: Thank you very much! Updated with pre

    ReplyDelete
  5. It looks like you were overzealous in copying the CSS from my comment: "to get around blogger stripping code and pre from comments." is not part of the CSS.

    ReplyDelete