Showing posts with label perlish code conciseness list manipulations. Show all posts
Showing posts with label perlish code conciseness list manipulations. Show all posts

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.