Introduction
A tcl for
loops takes in four arguments in the following order: initialisation, loop ending condition, next loop action, and main body code.
for loops
The following lines of code print integers from 0 until 4
for {set i 0} {$i < 5} {incr i} { puts "Counter: $i" }
Output:
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
foreach loops
foreach
loops are commonly used to deal with tcl lists. There is no need to initialize a counter variable or setting the condition to terminate a loop.
set Fruits [ list banana apple orange watermelon honeydew] foreach fruit $Fruits { puts "Fruit: $fruit" }
Output:
Fruit: banana
Fruit: apple
Fruit: orange
Fruit: watermelon
Fruit: honeydew
foreach
loops can also be used to handle multiple list objects:
set Fruits [ list banana apple orange watermelon honeydew] set Colours [ list yellow red orange red green] foreach fruit $Fruits colour $Colours { puts "Fruit: $fruit; colour: $colour" }
Output:
Fruit: banana; colour: yellow
Fruit: apple; colour: red
Fruit: orange; colour: orange
Fruit: watermelon; colour: red
Fruit: honeydew; colour: green
while loops
Tcl while
loops takes in only two arguments, loop ending condition and the main body code.
while {condition} {body}
set max_print 3 set counter 0 while { $counter < $max_print } { puts "Counter: $counter" set counter [expr $counter + 1] }
Output:
Counter: 0
Counter: 1
Counter: 2
Exiting or skipping loops
The continue
statement can be used to skip a loop if a certain condition met.
Taking below code as example, The continue
statement is used to skip printing “orange” .
set Fruits [ list banana apple orange watermelon honeydew] foreach fruit $Fruits { if {$fruit == "orange"} { continue } else { puts "Fruit: $fruit" } }
Output:
Fruit: banana
Fruit: apple
Fruit: watermelon
Fruit: honeydew
Use break
to exit a loop completely
set counter 0 while { $counter < 5 } { puts "Counter: $counter" set counter [expr $counter + 1] if { $counter == 3} { break } }
Output:
Counter: 0
Counter: 1
Counter: 2