Lists Are Strings, but Not All Strings Are Lists

Tcl's only data type is the string, and each command can interpret strings in special ways.[6] A list is a special interpretation of a string—a list of words separated by whitespace. Lists are a very powerful feature of Tcl: they are easy to visualize and can be formed from simple strings. This example creates the variable name from a string and then causes the string to be interpreted as a list with lindex:

set names "bob carol ted alice"
puts [lindex $names 2]

This code produces the following output:

ted

Trouble begins when lists are assembled from arbitrary strings that may contain special Tcl characters. For example, suppose you are writing a program to count the number of words in each line of a file. You notice that Tcl has an llength command, which returns the number of words in a list, and decide to use it:

set fd [open $somefile]
gets $fd aLine
while {! [eof $fd]} {
    puts "line has [llength $aLine] words"
    gets $fd aLine
}
close $fd

You start running your program, and all is well until you read a file that contains:

Tcl has several quoting characters, which
include { to mark the beginning of a fully
quoted string, up to a matching }.

Your program then fails with "unmatched open brace in list." The opening brace in the second line is interpreted as the beginning of a quoted string, possibly a list itself.

The key is to not use list commands on arbitrary strings, and use only list commands to build lists. Tcl even includes a list command ...

Get Tcl/Tk in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.