. Numeric Comparisons 101 - if .
[ Previous | Index | Next ]
Like most languages, Tcl supports an if command. The syntax is:
- if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?
The words then and else are optional, although generally then is left out and else is used. The test expression following if should return one of:
| False | True |
a numeric value | 0 | all others |
yes/no | no | yes |
true/false | false | true |
If the test expression returns a string "yes"/"no" or "true"/"false", the case of the return is not checked. True/FALSE or YeS/nO are legitimate returns.
If the test expression evaluates to True, then body1 will be executed. If the test expression evaluates to False, then the word after body1 will be examined. If the next word is elseif, then the next test expression will be tested as a condition. If the next word is else then the final body will be evaluated as a command.
The test expression following the word if is evaluated in the same manner as in the expr command. Hex strings 0xXX will be converted to their numeric equivalent before evaluation.
The test expression following if may be enclosed within quotes, or braces. If it is enclosed within braces, it will be evaluated within the if command, and if enclosed within quotes it will be evaluated during the substitution phase, and then another round of substitutions will be done within the if command.
--
. Example .
set x 1
if {$x == 2} {puts "$x is 2"} else {puts "$x is not 2"}
if {$x != 1} {
puts "$x is != 1"
} else {
puts "$x is 1"
}
if $x==1 {puts "GOT 1"}
set y x
if "$$y != 1" {
puts "$$y is != 1"
} else {
puts "$$y is 1"
}
|