Perl, a multi paradigm language

Perl is a great language. Not just because it is flexible, it has a great community, it has Larry Wall as its creator or because it has CPAN. Perl is a great language because it is multi-paradigm. That is, you can write Perl code in different ways, resembling imperative languages, functional languages or object-oriented languages (yes, we can discuss on this division, but that is not relevant at the moment).

What I want to say here is that I love to write functional programming lines with Perl. Check, for instance, on the task of reading a table (tab separated lines) with name, weight and height, and adding a new column with the BMI.

Can you do it on a single functional line?

perl -E 'say join("\n", map {join("\t", addBMI(split /\t/))}
map { s/\n//; $_ } <>);
sub addBMI { push @_, $_[-2]/$_[-1]**2; @_ };' weight.dat

I confess I cheated, defining a new function. Unfortunately push is not functional. Also substitution is not functional at the moment (being prepared on 5.13). Not sure if a functional push version would help. Probably not...


Many people still consider it a serious shortcoming that Perl code can be written in different ways, which at first glance seems like a perfectly valid argument. However, like you I believe that it provides the necessary extra flexibility to be more creative, making Perl a powerful programming language, indeed.

autobox::Core for having .push as arrayref method?

you don't really need to push:

sub addBMI { @_, $_[-2]/$_[-1]**2 }

Surely you don't even need to name a function.

map {join("\t", sub{ @_, $_[-2]/$_[-1]**2  }->(split /\t/))}
Though, perhaps it reads a little neater if you do :)

That’s not very idiomatic for a one-liner though.

perl -lnaF'\t' -E 'say join "\t", @F, $F[-2]/$F[-1]**2' weight.dat

Leave a comment

About Alberto Simões

user-pic I blog about Perl. D'uh!