www.gibmonks.com




  Previous section   Next section

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

Table of Contents
Chapter 1.  Tcl Fundamentals


Backslash Substitution

The final type of substitution done by the Tcl interpreter is backslash substitution. This is used to quote characters that have special meaning to the interpreter. For example, you can specify a literal dollar sign, brace, or bracket by quoting it with a backslash. As a rule, however, if you find yourself using lots of backslashes, there is probably a simpler way to achieve the effect you are striving for. In particular, the list command described on page 61 will do quoting for you automatically. In Example 1-8 backslash is used to get a literal $:

Example 1-8 Quoting special characters with backslash.
set dollar \$foo
=> $foo
set x $dollar
=> $foo

graphics/tip_icon.gif

Only a single round of interpretation is done.


The second set command in the example 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, which is described in Chapter 10.

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 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 part of the group and do 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.


      Previous section   Next section
    Top