Search code examples
tcl

Why is this mark wrong?


I'm learning tcl.

I wrote a code.

test.tcl

set design C
set Z 0
if {${design} == "A"} {
    set Z 5
} elseif {${design} == "B"} {
    set Z 10
#} elseif {${design} == "C"} {
#    set Z 15
} else {
    set Z 20
}

puts "Z = ${Z}"

then run: tclsh test.tcl

why I got the response: Z = 0

instead of: Z = 20

Can't I mark like this?


Solution

  • Tcl syntax is very straight-forward. Each command consists of a command name and zero or more arguments. In Tcl, the if command is like any other command. It is not treated special in any way. So, the Tcl interpreter takes your command and splits it into the command name (if) and the following list of arguments (whitespace reformatted for clarity):

    1. {${design} == "A"}
    2. {set Z 5}
    3. elseif
    4. {${design} == "B"}
    5. {set Z 10 ;#}
    6. elseif
    7. {${design} == "C"}
    8. {# set Z 15}
    9. else
    10. {set Z 20}

    The if command evaluates the first argument. It is 'false', so it skips the second argument. With the third argument being "elseif", it then checks the 4th argument. Continuing like this it eventually comes across argument #7, the {${design} == "C"} condition. This is not affected by the "#" inside argument #5. With $design actually having the value "C", this condition evaluates to 'true', causing argument #8 to be chosen as the body part to be executed. That argument has one line, starting with a "#", so it is treated as a comment. Now the if command has completed its job and Z remains unchanged.