Version 1 of What some command arguments expect

Updated 2004-07-13 10:20:22

This page is intended as to summarize some coding pitfalls I encountered in my early days of Tcl programming. As far as I know, this has not been issued anywhere else. Further contributions welcome -- RJM.

While coding, it is important to realize which type of argument is EXPECTED by the various Tcl commands. This saves unnecessary quotings or even erroneous quotings. Also superfluous commands could be entered as in this example:

 if [expr {$a < 0}] {set a 0}

Such silly sort of code lines may well occur when a beginner is getting confused about using the proper quoting. A more appropriate example is this:

 if {[command...] == xx} {
 for {[command...]} {..} {

(The curly braces may be omitted in the second example because the enclosed text is one word).

For a confused beginner, both lines seem to conform to a consistent syntax. Of course, the second case yields an error when the nested script does not return a valid command name. The beginner who is reading this should know that:

  • each command can have a "local" syntax of how to handle arguments. The expr command is one such command.
  • each argument may also be interpreted simply as tcl command/script, expr or the name of a variable.

The latter will be looked at briefly.

  • if expects an expression as its first argument, therefore no expr necessary.
  • for expects a command/script as its first argument, therefore no [] necessary.

The beginner must realize that the term "necessary" in the second example is incorrect. It suggests that where a command is expected, a []-quoting would be harmless doubling. It must be emphasized that [] does substitution just as $ also substitution. To be precise: [] is not "quoting". See also An Introduction to Tcl Scripting.

Further examples:

  • time expects a command as its first argument. time [command...] would substitute the script between [] upon Tcl parsing, and then the command time uses its result and treats this as a script.
  • switch is (at a first glance) confusing to C-programmers because they no see 'case'. The well defined order and interpretation of the switch arguments as 'pattern-body' pairs enables proper operation of switch.
  • incr expects a variable name. Perhaps a bit silly to notice that no $ is "necessary". But it may help a beginner to understand why sometimes not to use $ and when not. BTW: $ would effectively result in double dereferencing. See also deferencing.

A bit confusing for beginners is the use of list in -command options of Tk widgets or as the script argument of bind. The usage of [list .....] in [] results in immediate command subsitution. Its result is treated as the effective command/script for the -command option or binding. It's all in the "Division of Responsibility" Parser <-> Command: Any substitution is carried out during Parsing.


Category Tutorial