How does one sort in Tcl

What is sorting?

Sorting is taking a collection of things and putting them into some specific order. For example, sorting people by age, shoes by size, strings by length, planets by mass, numbers by value.

What techniques are available within the Tcl language?

  • lsort — takes a Tcl list argument and returns another list that is the sorted version of the input list. The other arguments determine exactly how the items in the list are to be ordered.

What are other relevant pages on the wiki?

Frequently Asked Questions about sorting

  • How can I sort the contents of a file in tcl?

For sorting the lines of a file being read from standard input, and writing the result out to standard output, one can use the following one-liner:

  puts [join [lsort [split [read -nonewline stdin] \n]] \n]

Or in English: read in all the data to sort, split it into the list of units to be sorted, sort that list, join the sorted list back up in the external format, and write it out.

A complication is that, as AMG observed, at least on Unix most files end with a newline. The split and join above interpret newlines as line separators, not line terminators, so if [split … \n] is applied to something whose the last character is a newline, it thinks a zero-length line follows. This is fixed by using the -nonewline option of read, which omits such a final newline. Not using the -nonewline option of puts furthermore normalises the output to end with a newline. (On Windows, \n inside Tcl furthermore corresponds to CRLF outside by default, so there is typically no need to worry about line-end conventions.)