arrows pointing right and left

Tcl’s Gist


email Scott Turner

the cheat sheet



home
programming
Tcl is defined operationally. A command does not receive a meaning until, at execution time, its name and arguments are fully substituted. At that time its meaning is simply to run the command and get its result.

For example, in the command
set foo [list a [bar] z]
you would expect the list to have 3 elements, and it does. But this is not because Tcl sees [bar] and sets things up to expect one argument. It's because bar's return command is rigged to return a representation of one value. A bare return will cause [bar] to be substituted with {}, while the command return a b is a run-time error. Thus, every command returns a representation of a single value.

Prime examples of how this differs from conventional languages are
  • String expressions can be juxtaposed for concatenation.
        set together [bar]$z
    
  • Arithmetic expressions are just strings, interpreted by the [expr ...] command.
As always in programming, it's necessary to keep track of the type of various variables and expressions. Although all values are strings, the strings that represent particular types such as lists and numbers need to agree with Tcl syntax and so should not be manipulated using string operations. It is tempting to do otherwise, since a programmer becomes aware of the Tcl representation when putting literal values into a program. The literals 4 and {4} have the same effect in normal contexts, though the former would be more familiar as a number and the latter as a string. The literal {} represents both the empty string and the empty list.

Functions and action procedures are indistinguishable. Any function can be named as an action and its result will be thrown away. Any command can be called as a function and it will return a value.

The upvar feature is awkward and exemplifies a flaw in Tcl. The problem is that Tcl has no references/pointers. From another point of view the problem is that objects are not first class. When another language would support passing by reference, in Tcl you can code it similarly ...
    doproc var
but this does not pass the object 'var', it passes the string var. You might think that the called procedure is up a creek, but think again ... there's the upvar hack. The calling procedure does
    upvar $param localvar
and localvar gets to be a synonym for the object named var.
    ... $localvar ...
home
programming

the cheat sheet

Support open standards!  
Valid XHTML 1.0!