List comprensions in Perl using map {}

In an earlier post I waxed lyrical about list comprehensions in Python. As a conterpoint, Justin Fletcher mailed me and gave me a version of most my examples using Perl. I’ve used Perl very little, but never really got on with it, so it was interesting to see how the two compared.

Justin says:

# 'for item in list' syntax
@list = (1,4,9,16,25);
foreach $i (@list)
    print "$i\n";

# arbitrary transformations
for $i (map { $_ * $_ } (1..5))
    print "$i\n";

# Parse key=value file.
open(IN, "< file");
%params = map { /^(.*?)=(.*)\n$/; ($1, $2) } <IN>;

He also gives an example of the reverse of the key=value example:

open(OUT, "> file") || die;
print OUT map { "$_=$params{$_}\n" } keys %params;

The Python equivalent I’d write would be:

out = open('file', 'w')
out.write("\n".join(["%s=%s" % item for item \
                     in params.items()])

Which I think is pretty similar. As Justin says, “I like comparing how you do things in different languages. It gives you a feel for strengths and weaknesses.”

Filed under: Coding
Posted at 14:47:00 GMT on 12th November 2007.

About Matt Godbolt

Matt Godbolt is a C++ developer working in Chicago for Aquatic. Follow him on Mastodon.