问题
In Tclers wiki page, at 'Dodeklogue' it is mentioned about comments:
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.
However, it seems that comments are interpreted byond the terminal \
: for example, let the content of file test.tcl be as below:
proc test {} {
# Open brace {
puts "I am fine"
}
test
t
Then
tclsh test.tcl
gives the following error message:
missing close-brace: possible unbalanced brace in comment
while executing
"proc test {} {"
(file "hello.tcl" line 1)
Even more interesting
Even more interesting, when the open brace {
is replaced with close brace }
, the error message is completely different.
Why does Tcl interpreter try to make sense of what is there in a comment, what would we lose if the Tcl interpretor (or any interpretor in general) was designed to take comments as real comments: once you see #
completely ignore until the new line (except, check last character of comment if it is \
) ?
回答1:
Tcl, unlike a number of other languages, processes comments at the same time as the rest of its syntax. This means that, because it came across a {
first (as part of the proc
command invocation) it is focusing on matching up the braces. It only comprehends a #
as a comment when it is evaluating the procedure (i.e., you call the command defined by the proc
command).
These will work as comments:
proc commentDemonstration {} {
puts "A"
# if [exit] {
puts "B"
# } else [exit]
puts "C"
}
# Call it and see, _no_ early exit
commentDemonstration
They are genuinely comments. It's just that you must balance (or backslash-quote) the braces in a procedure definition (unless you're mad enough to define a procedure body inside double quotes or something; don't do that for your own sanity's sake) independently of what comments you use. Most of the time you don't notice the balancing requirement, but this is one case where it matters.
Being able to put #
inside things like that is a key to embedding other languages inside Tcl. For example, Critcl allows C source code to be embedded within Tcl, and #
means something totally different in C.
来源:https://stackoverflow.com/questions/28127980/tcl-comments-why-interpret-comments