Tcl 评论:为什么解释评论?

Tcl comments: why interpret comments?

在 Tclers wiki 页面中,在 'Dodeklogue' 提到评论:

Comments: If # appears where a command is expected, the rest of the line is a comment. No command execution is attempted, and no characters in the line are interpreted, except that the terminating newline may be escaped with \, signifying that the comment continues on the subsequent line.

但是,注释似乎是由终端解释的\:例如,让文件test.tcl的内容如下:

proc test {} {
    # Open brace {
    puts "I am fine"
}

test

t

然后 tclsh test.tcl 给出以下错误消息:

missing close-brace: possible unbalanced brace in comment
    while executing
"proc test {} {"
    (file "hello.tcl" line 1)
Even more interesting

更有趣的是,当左大括号 { 被替换为右大括号 } 时,错误信息完全不同。

为什么 Tcl 解释器试图理解注释中的内容,如果 Tcl 解释器(或任何一般的解释器)被设计为将注释作为真正的注释,我们会失去什么:一旦你看到 # 完全忽略直到新行(除了,检查注释的最后一个字符是否为 \) ?

Tcl 与许多其他语言不同,它在处理注释的同时处理其语法的其余部分。这意味着,因为它首先遇到 {(作为 proc 命令调用的一部分),所以它专注于匹配大括号。它仅在 评估 过程(即调用由 proc 命令定义的命令)时将 # 理解为注释。

这些将用作评论:

proc commentDemonstration {} {
    puts "A"
    # if [exit] {
        puts "B"
    # } else [exit]
    puts "C"
}
# Call it and see, _no_ early exit
commentDemonstration

他们是真诚的评论。只是您必须平衡(或反斜杠引用)过程定义中的大括号(除非您疯狂到在双引号或其他东西内定义过程主体;不要这样做that 为了你自己的理智)独立于你使用的评论。大多数时候您不会注意到平衡要求,但这是一个很重要的情况。


能够将 # 放入类似的东西中是在 Tcl 中嵌入其他语言的关键。例如,Critcl 允许将 C 源代码嵌入到 Tcl 中,而 # 在 C 中意味着完全不同的东西。