XPS-Q8
Tcl Manual
declarations. Double quotes are useful in simple cases like the
puts
command shown
previously.
Another common use of quotes is with the
format
command. This is similar to the C
printf
function. The first argument to
format
is a format specifier, which often
includes special characters like newlines, tabs, and spaces. The easiest way to specify
such characters is with backslash sequences (e.g.,
\n
for newline and
\t
for tab). The
backslashes must be substituted before the
format
command is called, so you need to
use quotes to group the format specifier.
puts
[
format
"Item: %s\t%5.3f"
$name $value]
Here
format
is used to align a name and a value with a tab. The
%s
and
%5.3f
indicate how the remaining arguments are to be formatted by the
format
command .
Note that the trailing
\n
usually found in a C
printf
call is not needed because
puts
provides one for us.
2.2.6.1
Square Brackets Do Not Group
The square bracket syntax used for command substitution does not provide grouping.
Instead, a nested command is considered part of the current group. In the command
below, the double quotes group the last argument, and the nested command is just part
of that group.
puts
stdout "The
length
of $s is [
string
length
$s]."
If an argument is made up of a nested command, you do not need to group it with
double-quotes because the Tcl parser treats the whole nested command as part of the
group.
puts
stdout [
string
length
$s]
The following is a redundant use of double quotes:
puts
stdout
"[expr $x + $y]"
2.2.6.2
Grouping before Substitution
The Tcl parser makes a single pass through a command as it makes grouping decisions
and performs string substitutions. Grouping decisions are made before substitutions are
performed, which is an important property of Tcl. This means the values being
substituted will not affect grouping because the grouping decisions have already been
made.
The following example demonstrates how nested command substitution affects
grouping. A nested command is treated as an unbroken sequence of characters,
regardless of internal structure. It is included with the surrounding group of characters
when collecting arguments for the main command.
Example 1–11: Embedded command and variable substitution.
set
x
7
;
set
y
9
puts
stdout $x+$y=[
expr
$x + $y]
⇒
7+9=16
In Example 1–11, the second argument to
puts
is:
$x+$y=[
expr
$x + $y]
The white space inside the nested command is ignored for the purposes of grouping the
argument. By the time Tcl encounters the left bracket, it has already done some variable
substitutions to obtain:
7+9=
When the left bracket is encountered, the interpreter calls itself recursively to evaluate
the nested command. Again, the
$x
and
$y
are substituted before calling
expr
.
Finally, the result of
expr
is substituted for everything from the left bracket to the
right bracket. The
puts
command gets the following as the second argument:
7+9=16
EDH0307En1041 — 10/17
6