Tcl: Multiple Conditionals Inside the If Statement
Just Trying to Do Some Basic Check in a Script. .. to Produce an Error If $Argc Is Not Either 1 or 2. I Tried: If { ( $Argc! = 1 ) || ( $Argc! = 2 ) } { Puts...
Just trying to do some basic check in a script... to produce an error if $argc is not either 1 or 2.
I tried:
if { ( $argc != 1 ) || ( $argc != 2 ) } {
puts "ERROR: \$argc should be either 1 or 2.\n"; exit 1
}
and
if { ( $argc != 1 || $argc != 2 ) } {
puts "ERROR: \$argc should be either 1 or 2.\n"; exit 1
}
etc.
but couldn't make it work using any of the parenthesis/brace combinations.
Any help would be greatly appreciated.
2 Answers
This is basic logic.
Your example won't work because 2 is not equal to 1 so the first test is true.
To negate an OR conjunction, you negate each test and change the OR to an AND. You want this state:
if { ( $argc == 1 ) || ( $argc == 2 ) } {
puts "ok"
} else {
puts "ng"
}
So use:
if { ( $argc != 1 ) && ( $argc != 2 ) } {
# i.e. if $argc is either anything other than a 1 or a 2...
puts "ERROR: \$argc should be either 1 or 2.\n"; exit 1
}
Another way:
if {$argc ni {1 2}} { ... }
That is: if the value of argc is not in the list containing 1 and 2, ...
The ni operator requires Tcl 8.5 or later.
Documentation: if, ni (operator)