WilliamKF
WilliamKF

Reputation: 43179

Any way to embed a comment within a Tcl command?

I would like to have a comment within a command and it appears that this is not possible given that the '#' character is defined in Tcl 8.4 to be:

If a hash character (``#'') appears at a point where Tcl is expecting the first character of the first word of a command, then the hash character and the characters that follow it, up through the next newline, are treated as a comment and ignored. The comment character only has significance when it appears at the beginning of a command.

Imagine this example of how this might work (none of these comments worked in my experiments):

array set myArray [list red 3        \
                        blue 4       ;# Blue is before purple.
                        purple 5     # Purple is after red.
                        green 7      \
                        yellow 8]

Seems the tricky part is how to continue the list command with a comment embedded? Perhaps something like the C++ style of /* Embedded comment here. */ but I only see # as being used in Tcl for comments to end of line, nothing for begin and end comment syntax.

Upvotes: 3

Views: 3750

Answers (2)

Radek Liska
Radek Liska

Reputation: 251

Yes, there is a way to embed a comment into a command. It's not pretty, but it's possible. Add a command substitution containing only a comment to a list member, like this (the newline after the comment is mandatory):

array set myArray [list red 3     \
                        blue 4[
                                  # Blue is before purple.
                        ]         \
                        purple 5[
                                  # Purple is after red.
                        ]         \
                        green 7   \
                        yellow 8]
% array get myArray
yellow 8 purple 5 blue 4 green 7 red 3

Upvotes: 4

Bryan Oakley
Bryan Oakley

Reputation: 386155

No, you cannot embed a comment within the invocation of a command. Comments in Tcl don't quite work the same way as they do in other languages. Some people stumble over this, most experienced Tcl programmers don't give it a second thought.

The rare times that you truly need to do this you can usually work around it easily enough. Using your example:

set myArray(red) 3
set myArray(blue) 4 ;# Blue is before purple
set myArray(purple) 5 ;# Purple is after red
set myArray(green) 7
set myArray(yellow) 8

You might think this is slower than doing it all on one line but the difference is negligible in all but the most time-critical situations, probably on the order of just a few microseconds.

Upvotes: 6

Related Questions