Richard Suchenwirth 2002-12-06 - Tables are understood here as rectangular (matrix) arrangements of data in rows (one row per "item"/"record") and columns (one column per "field"/"element"). In Tcl, a sensible implementation would be as a list of lists.
A nice table also has a header line, that specifies the field name. So to create such a table with a defined field structure, but no contents yet, one just assigns the header list:
set tbl {{firstname lastname phone}}
Note the double bracing, which makes sure tbl is a 1-element list. Adding "records" to the table is as easy as
lappend tbl {John Smith (123)456-7890}
Here single bracing is correct. If a field content contains spaces, it must be quoted or braced too:
lappend tbl {{George W} Bush 234-5678}
Sorting a table can be done with lsort -index, taking care that the header line stays on top:
proc tsort args { set table [lindex $args end] set header [lindex $table 0] set res [eval lsort [lrange $args 0 end-1] [list [lrange $table 1 end]]] linsert $res 0 $header }
Removing a row (or contiguous sequence of rows) by numeric index is a job for lreplace:
set tbl [lreplace $tbl $from $to]
Simple printing of such a table, a row per line, is easy with
puts [join $tbl \n]
Accessing fields in a table is more fun with the field names than the numeric indexes, which is made easy by the fact that the field names are in the first row:
proc t@ {tbl field} {lsearch [lindex $tbl 0] $field} % t@ $tbl phone 2
You can then replace cell contents like this:
lset tbl $rownumber [t@ $tbl phone] (222)333-4567
See also matrix.