Previous section   Next section

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

Table of Contents
Chapter 1.  Tcl Fundamentals

Command Substitution

The second form of substitution is command substitution. A nested command is delimited by square brackets, [ ]. The Tcl interpreter takes everything between the brackets and evaluates it as a command. It rewrites the outer command by replacing the square brackets and everything between them with the result of the nested command. This is similar to the use of backquotes in other shells, except that it has the additional advantage of supporting arbitrary nesting of commands.

Example 1-3 Command substitution.
set len [string length foobar]
=> 6

In Example 1-3, the nested command is:

string length foobar

This command returns the length of the string foobar. The string command is described in detail starting on page 45. The nested command runs first.

Then, command substitution causes the outer command to be rewritten as if it were:

set len 6

If there are several cases of command substitution within a single command, the interpreter processes them from left to right. As each right bracket is encountered, the command it delimits is evaluated. This results in a sensible ordering in which nested commands are evaluated first so that their result can be used in arguments to the outer command.

      Previous section   Next section