Version 16 of Variable Substitution

Updated 2013-02-20 15:47:17 by pooryorick

ulis, 2003-08-31

See also

Description

Variable substitution is the way Tcl gets a value from a name:

set v aValue
puts $v

The $v notation tells Tcl to get the value of the variable v, whose value is

aValue

The $ notation was added to Tcl for coding convenience as a shorter way to express

set v

The following lines are equivalent:

puts $v
puts [set v]

When dynamically compoing a variable name, set can be used where $ can't. In the following example, Tcl substitutes the value of i and then set returns the value of var1, var2, var3.

foreach i {1 2 3} {puts [set var$i]}

The following code fails because Tcl tries to substitute $var and then $i, and finds that var is not defined.

#warning: example of bad code
foreach i {1 2 3} {puts $var$i} ;# this fails because $var is undefined

Another approach that is not recommended:

foreach i {1 2 3} {eval puts \$var$i}

Using the [set command in place of the $ variable can help to illuminate the behaviour of Tcl:

Replacing the $ notation by a $ call, the following lines are equivalent two by two:

foreach i {1 2 3} {puts $var$i} ;# this fails because $var is undefined
foreach i {1 2 3} {puts [set var][set i]} ;# this fails because $var is undefined

foreach i {1 2 3} {puts [set var$i]}
foreach i {1 2 3} {puts [set var[set i]]}

When accessing an array variable, the element name is computed and then looked up in the array, so arrays are a good fit when programming in a style that leads to composition of variable names:

foreach i {1 2 3} {set var($i) value$i}
foreach i {1 2 3} {puts $var($i)}

The last line is equivalent to:

foreach i {1 2 3} {puts [set var([set i])]}

Although variable indirection is considered bad style by some, it can be implemented as in the following example:

set a something
set pointer a
puts [set $pointer] ;#good style
puts [set [set pointer]] ;#more verbose style
eval puts \$$pointer ;#oh blimey, it's "eval"!  Run away!