Scalar Variables

Call by Value and Call by Name

Variables are first class citizens in Tcl: they can be manipulated like any other kind of data.

The set Command

Variable Substitution

While variable names can consist of any characters whatsoever, the variable substitution operator, $ assumes that your variable names consist only of alphanumerics and underscores. (This is probably good practice.) Note:

    set foo-bar 56
    puts $foo-bar
    => Error: can't read "foo": no such variable
The errror occurs because while hyphens are legal in variable names, $ doesn't recognize them.

There is a special notation to use with $ to refer to variables with exotic names:

    set foo-bar 56
    puts ${foo-bar}
    => 56

The unset Command

unset deletes the named variables and all storage associated with them. After an unset, any attempt to refer to the value of those variables results in an error.

The append Command

The obvious way to append more characters to the value of a variable foo is:

    set foo "$foo more text"

This can be inefficient when the value of foo is long, because it requires a copy. The append command achieves the same end with minimal copying:

    append foo " more text"

append takes any number of arguments (after the mandatory variable name) and appends them all to the variable, with no whitespace between any of them.

append returns the new value of the variable.

Note the use of call by name to side-effect the variable.

The incr Command

The obvious way to increment a variable n is:

    set n [expr $n + 1]
This bit of code is so important that Tcl provides a builtin command just to do this:

    incr n

incr returns the new (already incremented) value of the variable. (It's like C's ++ pre-increment operator.)

If the variable doesn't exist, incr returns an error condition.

incr is not only more convenient and easier to read, it saves two trips through the interpreter and one variable fetch and so is much more efficient.

incr takes an optional second argument which is the amount to increment the variable (the default is 1). This value can also be negative.

Note the use of call by name to side-effect the variable.

The info exists Command

Since it is an error to set or incr a variable that doesn't exist, Tcl provides a command to test the existence of a variable:

    info exists foo
returns 1 if foo exists, or 0 if it doesn't.

The info vars Command

info vars returns a list of all defined variables (in the current scope).
Keith Waclena
The University of Chicago Library
This page last updated: Mon Jul 25 14:14:06 CDT 1994
This page was generated from Extended HTML by xhtml.