Sorting Lines in 5 Languages

Jussi Pakkanen writes that C++ has become a scripting language. As evidence, he presents the following 19-line program in idiomatic C++11 which reads lines from the first command-line argument, sorts the lines, and writes them to the second argument.

I’m an incorrigible fan of C++ from days of old; I still prefer it to straight C for most low-level systems programming tasks. And I have to admit that this is admirably concise for a C++ program.

However, I thought it might be fun to see what this program looks like in other “scripting” languages. I used a file containing the following lines to test my implementations.

Starting with Ruby, since it’s what I spend most of my time in these days (this example has been updated with feedback from Joel VanderWerf):

This example is notable for using File.write , introduced in either 1.9.3 or 2.0, I can’t remember. It also uses ARGF to refer to “the concatenation of all files supplied on the command line”. At the point this is evaluated, the output file has already been pop’ed off of the ARGV array.

Next, a Perl version.

This being Perl, and my Perl being incredibly rusty, I’m sure it could be golfed down to a one-liner by a pro. In this code, the empty line-reading operator ( <>) serves the same purpose as ARGF.each_line above.

Now, how about an example using the grandparent of all scripting languages, TCL.

As you can see, TCL does not put the same premium on succinctness as some of the later scripting languages. Still, 9 lines ain’t bad.

Of course no comparison of scripting languages would be complete without an example in Bourne Shell:

EDIT: Stephen Ball points out that this is a superfluous use of cat. It should be:

To sum up, the C++ version is twice as long as the longest of my scripting language implementations. So while C++11 has made advances, I don’t think I’ll be using it for everyday scripting tasks anytime soon.

Thank you to Jussi Pakkanen for giving me an excuse to dust off my Perl and TCL skills. Writing these was an entertaining diversion.

UPDATE: Here are some more versions people have kindly contributed.

A Go version, from Bill Mill:

A Python version, also from Bill Mill, and incorporating feedback from commenter Keith:

Here it is in Elixir, from Eduardo Krustofski:

And here’s Clojure, from Ricardo Mendes:

A Rust version, from ajuckel:

Haskell, from Michael Xavier:

Lua, from Peter Aronoff:

PHP, from joonty:

Caius Durling contributed an AppleScript version, but since AppleScript has no built-in sort function it’s a bit long to include inline.

C#, from Ellyll: