XPS-Q8
Tcl Manual
Example 1–8: Quoting special characters with backslash.
set
dollar \$foo
⇒
$foo
set
x $dollar
⇒
$foo
Only a single round of interpretation is done.
The second
set
command in the example above illustrates an important property of
Tcl. The value of
dollar
does not affect the substitution performed in the assignment
to
x
. In other words, the Tcl parser does not care about the value of a variable when it
does the substitution. In the example, the value of
x
and
dollar
is the string
$foo
.
In general, you do not have to worry about the value of variables until you use
eval
.
You can also use backslash sequences to specify characters with their Unicode,
hexadecimal, or octal value:
set
escape \u001b
set
escape \0x1b
set
escape \033
The value of variable
escape
is the ASCII ESC character, which has character code
27
. The table on page 20 summarizes backslash substitutions.
A common use of backslashes is to continue long commands on multiple lines. This is
necessary because a newline terminates a command. The backslash in the next example
is required; otherwise the
expr
command gets terminated by the newline after the plus
sign.
Example 1–9: Continuing long lines with backslashes.
set
totalLength [
expr
[
string
length
$one] + \
[
string
length
$two]]
There are two fine points to consider when escaping newlines. First, if you are grouping
an argument as described in the next section, then you do not need to escape newlines;
the newlines are automatically a part of the group and will not terminate the command.
Second, a backslash as the last character in a line is converted into a space, and all the
white space at the beginning of the next line is replaced by this substitution. In other
words, the backslash-newline sequence also consumes all the leading white space on the
next line.
2.2.6
Grouping with Braces and Double Quotes
Double quotes and curly braces are used to group words together into one argument.
The difference between double quotes and curly braces is that quotes allow substitutions
to occur in the group, while curly braces prevent substitutions. This rule applies to
command, variable, and backslash substitutions.
Example 1–10: Grouping with double quotes vs. braces.
set
s Hello
⇒
Hello
puts
stdout
"The length of $s is [string length $s]."
⇒
The length of Hello is 5.
puts
stdout {The length of $s is [string length $s].}
⇒
The length of $s is [string length $s].
In the second command of Example 1–10, the Tcl interpreter does variable and
command substitution on the second argument to
puts
. In the third command,
substitutions are prevented, so the string is printed as is. In practice, grouping with curly
braces is used when substitutions on the argument must be delayed until a later time (or
never at all). Examples include loops, conditional statements, and procedure
EDH0307En1041 — 10/17
5