Tcl/Tk注释符#详解
Tcl中注释标识符用的是#,下面将通过实例讲解Tcl/Tk中注释符的用法及需要注意的问题。
1)
# This is a comment
set a 100 #Not a comment
解析:#必须出现在Tcl预期将获得命令的第一个字符上,否则将当作普通字符处理。上面第一句是正确的注释,第二句会把#及其后面的单词全部当作set的 单词处理,set后面出现五个参数,将提示以下错误:“wrong # args: should be "set varName ?newValue?"“。
(2)
set b 100 ;# This is a comment
输出:100
解析:正确的注释。
(3)
set example {
# This is not a comment
}
输出: # This is not a comment
解析:大括号起到了替换作用。大括号中的所有字符都将当作一个参数而赋给set指定的变量exanple。
(4)
proc test {x} {
if {$x<0} {
#This is a comment.
puts "The result is negative."
}
}
输入:test -1
输出:The result is negative.
解析:if的第二个参数被视为脚本,在脚本解析中#开头的行被视为注释。
(5)
proc countdown {x} {
puts "Running countdown"
#Incorrectly comment out this code block {
while {$x>=0} {
puts "x = $x"
incr x -1
}
}
}
输入:countdown 5
输出:Running countdown
x = 5
x = 4
x = 3
x = 2
x = 1
x = 0
invalid command name "}"
解析:#后面的整行都被当作注释忽略掉,因此大括号无法配对。注释中应尽量避免使用大括号,如果需要使用大括号则要保证注释中的大括号也是配对的。如下:
proc countdown {x} {
puts "Running countdown"
# while {$x>=0} {
#puts "x = $x"
#incr x -1
#}
}
一般,如果需要将某个代码片段注释掉,常用以下方法:
proc countdown {x} {
puts "Runnning countdown"
if 0 {
while {$x>=0} {
puts "x = $x"
incr x -1
}
}
}