Main Content

Curley brackets v double quotes - Tcl, Tk, Expect

Archive - Originally posted on "The Horse's Mouth" - 2007-12-12 23:18:38 - Graham Ellis

In Tcl, both Curley braces and double quotes can be used to hold a block of program or data together as a single unit / parameter ... but there are differences ...

a) Curley braces can stretch over a number of lines, with new lines within the block being simply a part of the block. So they're ideal for defining blocks of code
b) Curley braces can be nested - since there are different open and close characters, blocks within blocks are written easily and naturally, which is quite impractical with double quotes!
c) the biggest difference is that double quoted blocks are evaluated at the time they are encountered by the language parser, but curley braces are deferred until they are (perhaps) evaluated later under the control of the command of which they form a part.

Let's see an example - I've defined two procs with identical code in the body, but one is done with braces and the other with quotes:

set sample 5
 
proc demo {} {global sample; return $sample}
proc omed {} "global sample; return $sample"
 
set sample 27
 
puts "Curley braces - defer substitution until block is run"
puts [demo]
puts "Double quotes - just grouping; substition at definition time"
puts [omed]
 
puts [info body demo]
puts [info body omed]


The first proc - demo - has a DEFERRED block which means that the $sample variable isn't evaluated until the proc is RUN.

The second proc - omed - has an IMMEDIATE block which means that the $sample variable is evaluated as the proc is being DEFINED and the proc always returns "5" ...

The info body command allows you to see the contents of your procs ... not a very common requirement, but wonderful for a demonstration like this one!

Here it is, run ...

Dorothy:dectcl grahamellis$ tclsh t2
Curley braces - defer substitution until block is run
27
Double quotes - just grouping; substition at definition time
5
global sample; return $sample
global sample; return 5
Dorothy:dectcl grahamellis$