Now we’re ready to discuss the third type of substitution,
command substitution.
Recall that every command
returns a string result. Command substitution allows us to replace a complete Tcl command with its result
for use in an enclosing command. To use it, just enclose a command inside square brackets:
[]
. For example:
% set x 4
4
% set y 7
7
% set z [expr $x * $y]
28
%
Arrays
So far, the variables we’ve used have been
simple variables,
also called
scalar.
Tcl also provides another
kind of variable, called an
associative array.
An associative array is a collection of different values which are
indexed by a string (the element name). This is a very powerful mechanism, and associative arrays are used
extensively in Amanda Portal.
Array elements thus have two names: the name of the array plus the name of the element. The element
name is enclosed in parentheses. It may be a constant or a variable (or a combination), so long as it doesn’t
contain a space. If the element name has a space, then the entire variable name must be quoted to “hide”
the space.
For example, we could collect information on a person this way:
set person(name) "Tim Morgan"
set person(age) 37
set person(address) "23822 Brasilia Street"
set person(city) "Mission Viejo"
set person(state) California
set person(zip) 92691
On the other hand, if we have information about a number of people, we might use one array per attribute,
and use the names as the indices:
set age(Tim) 37
set address(Tim) "23822 Brasilia Street"
set city(Tim) "Mission Viejo"
set state(Tim) California
set zip(Tim) 92691
set age(Siamak) 36
set address(Siamak) "26321 Eva Street"
set city(Siamak) "Laguna Hills"
set state(Siamak) California
set zip(Siamak) 92656-3108
We can use the values in the array pretty much just as with simple variables:
11