Comparing loop commands in Tcl
Archive - Originally posted on "The Horse's Mouth" - 2012-01-06 17:41:13 - Graham EllisTcl offers you three different loop commands - here they are generating the same output:
while A condition is tested, and if true the commands in a loop are performed. The condition is then retested (provided that you have passed the test into while as a deferred block)
set month 1
while {$month <= 12} {
puts "2. This is for month $month"
incr month
}
for A prettified version of while - it takes two extra parameters which are normally used to initialise a variable, and to increment that variable before the test is redone.
for {set month 1} {$month <= 12} {incr month} {
puts "1. This is for month $month"
}
foreach Run a block of code (a loop) for each value in a list.
foreach month {1 2 3 4 5 6 7 8 9 10 11 12} {
puts "3. This is for month $month"
}
The latter is significantly different in its use and intent.
See full program [here].
All loops taught / covered / compared on our Tcl and Tcl/Tk courses.