www.gibmonks.com

  Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Part II.  Advanced Tcl


Chapter 10. Quoting Issues and Eval

This chapter describes explicit calls to the interpreter with the eval command. An extra round of substitutions is performed that results in some useful effects. The chapter describes the quoting problems with eval and the ways to avoid them. The uplevel command evaluates commands in a different scope. The subst command does substitutions but no command invocation.

Dynamic evaluation makes Tcl flexible and powerful, but it can be tricky to use properly. The basic idea is that you create a string and then use the eval command to interpret that string as a command or a series of commands. Creating program code on the fly is easy with an interpreted language like Tcl, and very hard, if not impossible, with a statically compiled language like C++ or Java. There are several ways that dynamic code evaluation is used in Tcl:

  • In some cases, a simple procedure isn't quite good enough, and you need to glue together a command from a few different pieces and then execute the result using eval. This often occurs with wrappers, which provide a thin layer of functionality over existing commands.

  • Callbacks are script fragments that are saved and evaluated later in response to some event. Examples include the commands associated with Tk buttons, fileevent I/O handlers, and after timer handlers. Callbacks are a flexible way to link different parts of an application together.

  • You can add new control structures to Tcl using the uplevel command. For example, you can write a function that applies a command to each line in a file or each node in a tree.

  • You can have a mixture of code and data, and just process the code part with the subst command. For example, this is useful in HTML templates described in Chapter 18. There are also some powerful combinations of subst and regsub described in Chapter 11.


      Previous section   Next section
    Top