Comments Are Treated as Commands

Comments in Tcl can be another source of frustration if the Tcl syntax rules are misinterpreted. Comments look like those in shell-type languages, a line that begins with a “#”. However, Tcl fully parses lines before deciding that they should be executed (in the case of a command) or ignored (in the case of a comment). You should think of a comment as a “do nothing” command, rather than as a comment as in other languages. Comments may appear where Tcl expects a command to appear.

Two common problems arise when comments are included in the arguments of a command or are used to temporarily remove sections of code during testing or development. The switch command illustrates the first problem. Switch arguments include a test string followed by one of more pairs of patterns and Tcl code blocks. The problem in the following example occurs when comments are inserted among the pattern-code pairs:

switch $code {
    # decode red, green, blue color codes
    r {set color red}
g {set color green}
    b {set color blue}
    default {puts "oops, unknown color code"}
}

Since the switch command expects pairs of patterns and code blocks, the beginning “#” of the comment line is interpreted to be a pattern, followed by a code block (literally “decode”), another pattern (“r ed”) with the code block “green,” and so on. Tcl will announce “extra switch pattern with no body” if there is an odd number of words in the comment line, or perhaps yield an “invalid command name” if there is an ...

Get Tcl/Tk in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.