Controlling flow with the if statement
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.
How to do it…
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
How it works…
The if
command...