Module 28 min

Variables and Substitution

set, $, [ ], and expr

Everything in TCL builds on three kinds of substitution. Learn these and you can read most scripts.

Setting and reading variables

tcl
set clk_period 1.25        ;# create a variable (no $ when setting)
puts $clk_period           ;# read it with $  ->  1.25
set design "spm"
puts "Design is $design"    ;# variables expand inside double quotes

The three substitutions

  1. Variable substitution: $name is replaced by the value of name.
  2. Command substitution: [command] runs the command and is replaced by its result.
  3. Backslash substitution: \ escapes a special character or continues a line.
tcl
# Command substitution: the inner command runs first
set num_cells [sizeof_collection [get_cells *]]
puts "There are $num_cells cells"

# Math needs expr - TCL does not do arithmetic on its own
set half [expr {$clk_period / 2.0}]   ;# 0.625
Watch out

TCL does not do math automatically. set x 2+2 makes x the string "2+2", not 4. You must use expr: set x [expr {2 + 2}]. Always wrap the expression in braces { } inside expr for speed and to avoid double substitution. This trips up everyone at first.

Quotes versus braces

Double quotes allow substitution inside them: "$design" becomes the value. Braces do not: {$design} stays literally $design. This matters constantly. Use quotes when you want variables expanded, braces when you want the text left alone, such as in expr and in command bodies.

Pro tip

the difference between " " and { } is the single most useful thing to internalize in TCL. Quotes substitute, braces do not. Most beginner bugs are using one where the other was needed.