Evaluating Lists As Commands
Everything in Tcl is represented as a string. This includes commands. You can manipulate commands just like any other string. Here is an example where a command is stored in a variable.
tclsh>set output "puts"puts tclsh>$output "Hello world!"Hello world!
The variable output could be used to select between several different forms of output. If this command was embedded inside a procedure, it could handle different forms of output with the same parameterized code. The Tk extension of Tcl uses this technique to manipulate multiple widgets with the same code.
Evaluating an entire command cannot be done the same way. Look what happens:
tclsh>set cmd "puts \"Hello world!\""puts "Hello world!" tclsh>$cmdinvalid command name "puts "Hello world!""
The problem is that the entire string in cmd is taken as the command name rather than a list of a command and arguments.
In order to treat a string as a list of a command name and arguments, the string must be passed to the eval command. For instance:
tclsh> eval $cmd
Hello world!
The eval command treats each of its arguments as a list. The elements from all of the lists are used to form a new list that is interpreted as a command. The first element become the command name. The remaining elements become the arguments to the command.
The following example uses the arguments "append“, "v1“, "a b“, and "c d" to produce and evaluate the command "append v1 a b c d“.
tclsh> eval append v1 "a b" "c d"
abcdRemember the
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access