The if
command evaluates a condition and if the condition evaluates to true, the actions are performed. The condition must be Boolean. With the addition of the else
and elseif
keywords, multiple conditions may be evaluated and numerous actions can be performed.
In the following recipe, we will create a Tcl script to be called from the command line that evaluates the argument passed, and based on the argument provided, perform an action.
Create a text file named if.tcl
that contains the following commands:
# Set the variable x to the argument set x [lindex $argv 0] # Test for condition 1 if {$x == 1} { puts "Condition 1 - You entered: $x" # Test for condition 1 } elseif {$x == 2} { puts "Condition 2 - You entered: $x" # If neither condition is met perform the default action } else { puts "$x is not a valid argument" }
Now invoke the script using the following command line:
tclsh85 if.tcl 1
Condition 1 - You entered: 1
The if
command has evaluated the argument passed; based on the argument value passed, it has evaluated the argument. As condition 1
was met, the first action was performed.
Now invoke using the following command line:
tclsh85 if.tcl 2
You entered: 2
As condition 2
was met, the second action was performed.
Now invoke using the following command line:
tclsh85 if.tcl x
x is not a valid argument
The if
construct also provides the then
keyword. When using multiple conditions, the then
keyword can optionally be used for clarity, as you can see in the following example:
if { $x in {1 2 3} } then { puts "$x" }
Try rewriting the if.tcl
script using multiple conditional statements.
3.21.46.92