TCL_control_flow
TCL_control_flow
Control flow statements in TCL include if, while, for, foreach, switch, and eval.
the result.
if command receives two arguments. First is an expression and the second is a Tcl script.
if command can also include one or more elseif clauses with additional tests and scripts, plus a final
Example
if {$x < 0} {
...
} elseif {$x == 1} {
...
} else {
...
}
3 VIT - SENSE 09-01-2024
Looping commands
Tcl provides three commands for looping: while, for, and foreach.
While Command :
The while command takes two arguments: an expression and a Tcl script.
It evaluates the expression and if the result is non-zero then it executes the Tcl script.
This process repeats over and over until the expression evaluates to zero, at which point the while
set a [list x y z]
set b ""
incr i -1
The for command is similar to while except that it provides more explicit loop control.
set a {w x y z}
set b ""
Foreach takes three arguments. The first is the name of a variable, the second is a list, and the third is a
Foreach will execute the body script once for each element of the list, in order.
Before executing the body in each iteration, foreach sets the variable to hold the next element of the list.
set a {w x y z}
set b "";
foreach i $a {
Example:
suppose the list reversal example above it is desired to stop as soon as an element equal to a particular
value is found in the source list then we can use the break command.
set b "";
foreach i $a {
Example :
set b ""
foreach i $a {
The same effect as switch can be achieved with an if command that has lots of elseif clauses,
The first argument in each pair is a pattern to compare against the value.
As soon as it finds a match it executes the corresponding script and returns the value of that script as its
value.
This form spreads the patterns and scripts into separate arguments.
First form is preferable because you can easily spread the patterns and scripts across multiple lines
like this:
switch $x {
a {incr t1}
b {incr t2}
c {incr t3}
Example :
switch $x {
a-
b-
c {incr t1}
d {incr t2}
It accepts any number of arguments, concatenates them together with separator spaces, and then
One use of eval is for generating commands, saving them in variables, and then later evaluating the
Example :
...
eval $cmd
In the above example variable a is set to 0 when the eval command is invoked.
Perhaps the most important use for eval is to force another level of parsing.
The results of one substitution are not reparsed for other substitutions.
Suppose a variable vars contains a list of variables and you wish to unset each of these variables then the
unset $vars
Eval generates a string consisting of “unset ” followed by the list of variable names and then passes the string
Example :
source init.tcl
The above command will execute the contents of the file init.tcl.
gets stdin c;
if {$f<40} {
} elseif {$f>80} {
} else {