Previous section   Next section

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

Table of Contents
Chapter 1.  Tcl Fundamentals

More about Variables

The set command will return the value of a variable if it is only passed a single argument. It treats that argument as a variable name and returns the current value of the variable. The dollar-sign syntax used to get the value of a variable is really just an easy way to use the set command. Example 1-15 shows a trick you can play by putting the name of one variable into another variable:

Example 1-15 Using set to return a variable value.
set var {the value of var}
=> the value of var
set name var
=> var
set name
=> var
set $name
=> the value of var

This is a somewhat tricky example. In the last command, $name gets substituted with var. Then, the set command returns the value of var, which is the value of var. Nested set commands provide another way to achieve a level of indirection. The last set command above can be written as follows:

set [set name]
=> the value of var

Using a variable to store the name of another variable may seem overly complex. However, there are some times when it is very useful. There is even a special command, upvar, that makes this sort of trick easier. The upvar command is described in detail in Chapter 7.

Funny Variable Names

The Tcl interpreter makes some assumptions about variable names that make it easy to embed variable references into other strings. By default, it assumes that variable names contain only letters, digits, and the underscore. The construct $foo.o represents a concatenation of the value of foo and the literal ".o".

If the variable reference is not delimited by punctuation or white space, then you can use curly braces to explicitly delimit the variable name (e.g., ${x}). You can also use this to reference variables with funny characters in their name, although you probably do not want variables named like that. If you find yourself using funny variable names, or computing the names of variables, then you may want to use the upvar command.

Example 1-16 Embedded variable references.
set foo filename
set object $foo.o
=> filename.o
set a AAA
set b abc${a}def
=> abcAAAdef
set .o yuk!
set x ${.o}y
=> yuk!y

The unset Command

You can delete a variable with the unset command:

unset varName varName2 ...

Any number of variable names can be passed to the unset command. However, unset will raise an error if a variable is not already defined.

Using info to Find Out about Variables

The existence of a variable can be tested with the info exists command. For example, because incr requires that a variable exist, you might have to test for the existence of the variable first.

Example 1-17 Using info to determine if a variable exists.
if {![info exists foobar]} {
   set foobar 0
} else {
   incr foobar

Example 7-6 on page 86 implements a new version of incr which handles this case.

      Previous section   Next section