An Introduction To Tcl Scripting, by John Ousterhout, with some where necesary to reflect modern Tcl.
Two parts to learning Tcl:
1. Syntax and substitution rules:
2. Built-in commands:
Basics:
Tcl script =
Tcl command =
Examples:
set a 22; set b 33 set a 22 set b 33
Division Of Responsibility
The Tcl Parser
The substitutions carried out by the parser are "one step"; the values substituted are not scanned again for text that looks like substitutions. Some specific commands ([eval], [expr], [subst], ...) perform another round of substitution on their arguments.
Arguments
C:
x = 4; y = x+10;
Result: y is 14
Tcl:
set x 4; set y x+10
Result: y is x+10
set a 122 expr 24/3.2 eval "set a 122" button .b -text Hello -fg red string length Abracadabra
Variable Substitution
Sample command Result set b 66 66 set a b b set a $b 66 set a $b+$b+$b 66+66+66 set a $b.3 66.3 set a $b4 no such variable
Command Substitution
set b 8 #-> 8 set a [expr {$b+2}] #-> 10 set a "b-3 is [expr {$b-3}]" #-> b-3 is 5
Controlling Word Structure
set a "x is $x; y is $y"
set a {[expr {$b*$c}]}
set a word\ with\ \$\ and\ space
set a {two words} set b $a
Expressions
Sample command Result set b 5 5 expr ($b*4) - 3 17 expr $b <= 2 0 expr $a * cos(2*$b) -5.03443 expr {$b * [fac 4]} 120 set a Bill Bill expr {$a < "Anne"} 0
Lists
red green blue
a b {c d e} f one\ word two three
lindex {a b {c d e} f} 2 #-> c d e lsort {red green blue} #-> blue green red
Control Structures
set b {} set i [expr [llength $a] - 1] while {$i >= 0} { lappend b [lindex $a $i] incr i -1 }
Procedures
proc sub1 x {expr $x-1} ^ ^ ^ | | | name | body | list of argument names
sub1 3 -> 2
proc decr {x {y 1}} { expr $x-$y }
proc sum args { set s 0 foreach i $args { incr s $i } return $s } sum 1 2 3 4 5 #-> 15 sum #-> 0
Errors
set n 0 foreach i {1 2 3 4 5} { set n [expr {$n + i*i}] } #-> syntax error in expression "$n + i*i"
set errorInfo
result:
syntax error in expression "$n + i*i" while executing "expr {$n + i*i}" invoked from within "set n [expr {$n + i*i}]..." ("foreach" body line 2) ...
Advanced Error Handling
catch {expr {2 +}} msg #-> 1 set msg #-> syntax error in expression "2 +"
error "bad argument"
(e.g. UNIX errno value).
Additional Tcl Features:
exec grep foo << $input | wc
set x(fred) 44 set x(2) [expr $x(fred) + 6] array names x #-> fred 2
More On Substitutions
exec rm *.o ;#-> *.o: No such file or directory glob *.o ;#-> a.o b.o exec rm [glob *.o] ;#-> a.o b.o: No such file or directory exec rm {*}[glob *.o] eval exec rm [glob *.o]
----Commands And Lists: Tcl Quoting
button .b -text Reset -command {set x $initValue} ;#(initValue read when button invoked) ... -command "set x $initValue" ;#(fails if initValue is "New York": command is "set x New York") ... -command "set x {$initValue}" ;#(fails if initValue is "{": command is "set x {{}") ... -command [list set x $initValue] ;#(always works: if initValue is "{" command is "set x \{")
Tcl Syntax Summary