Tcl Substitutions

Substitutions

When writing Tcl applications, a lot of time is spent on gettting substitutions to happen when you want them to.

Substitutions are marked by the special characters:

Character Meaning
$ Variable substitution
[ and ] Command substitution, note that because these delimeters are directional, nested command substitution is possible.
\ Backslash substitution, is used to insert special characters such as newlines (\n) and tabs (\t).

Quoting

Quoting is done using the following characters:

Character Meaning
" Stops any contained word separators from doing their thing. This means that spaces and semicolons lose their special meanings when inside a string surrounded by double quotes.
{ and } Stops any contained word separators from doing their thing, as well as stopping substitutions. This means that spaces, dollar signs and square brackets lose their special meanings inside curly quotes.
\ Stops the following character from having any special meaning.

Examples of Substitution and Quoting

  1. A simple example of variable substitution: set a foo set b bar set c baz set d $a$b$c puts $d which outputs: foobarbaz
  2. An example of command substitution: set answer [ expr 5 * 4 ] puts $answer outputs: 20
  3. An example of backslash substitution: set twoLines line1\nline2 puts $twoLines which outputs: line1 line2
  4. A string with spaces. One way to have a string with spaces is to quote each space: set aString some\ words\ with\ some\ spaces\ inbetween. puts $aString with outputs: some words with some spaces inbetween. If, however, you don't like to get headaches: set aString "some words with some spaces inbetween." puts $aString
  5. Defering substitution. This method of quoting is used to pass around bits of code: set test {expr $i <= 10} puts $test outputs: expr $i <= 10 That is, absolutely nothing is touched inside the curly brackets.

Previous Contents Next
Clinton Roy