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>;
close(IN);
He also gives an example of the reverse of the key=value example:
open(OUT,"> file")||die;
printOUTmap{"$_=$params{$_}\n"}keys%params;
close(OUT);
The Python equivalent I’d write would be:
out = open('file', 'w')
out.write("\n".join(["%s=%s" % item for item \
in params.items()])
out.close()
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.”
Matt Godbolt is a C++ developer living in Chicago. He works for Hudson River Trading on super fun but secret things. He is one half of the Two's Complement podcast. Follow him on Mastodon or Bluesky.
Copyright 2007-2026 Matt Godbolt. Unless otherwise stated, all content is licensed under the Creative Commons Attribution-Noncommercial 3.0 Unported License. This blog is powered by the MalcBlogSystem by Malcolm Rowe. Note: This is my personal website. The views expressed on these pages are mine alone and not those of my employer.