Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 5.  Tcl Lists

Sorting Lists: lsort

You can sort a list in a variety of ways with lsort. The list is not sorted in place. Instead, a new list value is returned. The basic types of sorts are specified with the -ascii, -dictionary, -integer, or -real options. The -increasing or -decreasing option indicate the sorting order. The default option set is -ascii -increasing. An ASCII sort uses character codes, and a dictionary sort folds together case and treats digits like numbers. For example:

lsort -ascii {a Z n2 n100}
=> Z a n100 n2
lsort -dictionary {a Z n2 n100}
=> a n2 n100 Z

You can provide your own sorting function for special-purpose sorting. For example, suppose you have a list of names, where each element is itself a list containing the person's first name, middle name (if any), and last name. The default sorts by everyone's first name. If you want to sort by their last name, you need to supply a sorting command.

Example 5-7 Sorting a list using a comparison function.
proc NameCompare {a b} {
   set alast [lindex $a end]
   set blast [lindex $b end]
   set res [string compare $alast $blast]
   if {$res != 0} {
      return $res
   } else {
     return [string compare $a $b]
set list {{Brent B. Welch} {John Ousterhout} {Miles Davis}}
=> {Brent B. Welch} {John Ousterhout} {Miles Davis}
lsort -command NameCompare $list
=> {Miles Davis} {John Ousterhout} {Brent B. Welch}

The NameCompare procedure extracts the last element from each of its arguments and compares those. If they are equal, then it just compares the whole of each argument.

Tcl 8.0 added a -index option to lsort that can be used to sort lists on an index. Instead of using NameCompare, you could do this:

lsort -index end $list

      Previous section   Next section