set
Commandset
returns the
value of variable. An error occurs if there is no such variable.
set
changes the
value of the variable to the second argument. If the variable doesn't
exist, it is created.$
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 variableThe 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
unset
Commandunset
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.
append
Commandset 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.
incr
Commandset 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.
info exists
Commandset
or incr
a
variable that doesn't exist, Tcl provides a command to test the
existence of a variable:
info exists fooreturns 1 if foo exists, or 0 if it doesn't.
info vars
Commandinfo vars
returns a list of all defined variables (in the
current scope).