Attempting to set two variables values according to the user input in a third variable. I am trying to use a switch statement but I am not sure if it is actually possible.
switch $sample_type_input {
CORE { set sample_type 1 \
set cutting ""}
SWC { set sample_type 2 \
set cutting ""}
CUTT { set sample_type 3 \
set cutting "CUTT" }
}
I keep getting a 'wrong # args: should be "set varName ?newBalue?"` error.
The backslash at the end of the line acts as a line continuation, concatenating this line and the next line into a single logical line of code. This is necessary in a case where one has to break up a command invocation into two or more lines, because of the parsing rules:
set foo
bar
is interpreted as two command invocations: set foo
and bar
.
set foo \
bar
is a single command invocation: set foo bar
.
Note that the backslash must be the very last character before the newline: e.g. a space between the backslash and the newline simply makes the invocation end with a regular space and a quoted space:
# there is a space after the backslash here
set foo \
puts "{$foo}"
# => { }
If your command invocation includes an argument in braces, it's typically quite all right to break it up into several lines without a backslash, since all whitespace including newlines is quoted by the braces anyway:
set foo {
bar
baz
}
And indeed if the argument within braces is a script containing more than one command invocation, you need to break it up into lines (or insert semicolons), since newlines are significant as command line separators. Therefore this fails:
if {true} {set foo bar \
set baz quz}
as it concatenates two command invocations into the single code line set foo bar set baz quz
, providing the set
command with five arguments when it expects one or two. The correct way is to write it as
if {true} {set foo bar ; set baz quz}
or
if {true} {set foo bar
set baz quz}
letting the semicolon or newline separate the command invocations in the script argument. Stylistic convention is to add additional newlines at the beginning and end of a multi-line script argument, like this:
if {true} {
set foo bar
set baz quz
}
This is similar to C brace styles, but not quite the same thing. One common beginner mistake is to try to use some other C bracing convention such as
if {true}
{
set foo bar
set baz quz
}
which won't work since it introduces a codeline-separating newline between the first and second arguments to if
. If you can't live without this bracing convention, you need to add a line continuation:
if {true} \
{
set foo bar
set baz quz
}
Documentation: if, puts, set, Summary of Tcl language syntax
(Note: the 'Hoodiecrow' mentioned in the comments is me, I used that nick earlier.)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments