One difference between Tcl and most other compilers is that Tcl will allow an executing program to create new commands and execute them while running.
A tcl command is defined as a list of strings in which the first string is a command or proc. Any string or list which meets this criteria can be evaluated and executed.
The eval command will evaluate a list of strings as though they were commands typed at the % prompt or sourced from a file. The eval command normally returns the final value of the commands being evaluated. If the commands being evaluated throw an error (for example, if there is a syntax error in one of the strings), then eval will throw an error.
Note that either concat or list may be used to create the command string, but that these two commands will create slightly different command strings.
set cmd {puts "Evaluating a puts"} puts "CMD IS: $cmd" eval $cmd if {[string match [info procs newProcA] ""] } { puts "\nDefining newProcA for this invocation" set num 0; set cmd "proc newProcA " set cmd [concat $cmd "{} {\n"] set cmd [concat $cmd "global num;\n"] set cmd [concat $cmd "incr num;\n"] set cmd [concat $cmd " return \"/tmp/TMP.[pid].\$num\";\n"] set cmd [concat $cmd "}"] eval $cmd } puts "\nThe body of newProcA is: \n[info body newProcA]\n" puts "newProcA returns: [newProcA]" puts "newProcA returns: [newProcA]" # # Define a proc using lists # if {[string match [info procs newProcB] ""] } { puts "\nDefining newProcB for this invocation" set cmd "proc newProcB " lappend cmd {} lappend cmd {global num; incr num; return $num;} eval $cmd } puts "\nThe body of newProcB is: \n[info body newProcB]\n" puts "newProcB returns: [newProcB]"
CMD IS: puts "Evaluating a puts" Evaluating a puts Defining newProcA for this invocation The body of newProcA is: global num; incr num; return "/tmp/TMP.10312.$num"; newProcA returns: /tmp/TMP.10312.1 newProcA returns: /tmp/TMP.10312.2 Defining newProcB for this invocation The body of newProcB is: global num; incr num; return $num; newProcB returns: 3