Foreach

The foreach command loops over a command body assigning one or more loop variables to each of the values in one or more lists. Multiple loop variables were introduced in Tcl 7.5. The syntax for the simple case of a single variable and a single list is:

foreach loopVar valueList commandBody
					

The first argument is the name of a variable, and the command body is executed once for each element in the list with the loop variable taking on successive values in the list. The list can be entered explicitly, as in the next example:

Example 6-8 Looping with foreach.
set i 1
foreach value {1 3 5 7 11 13 17 19 23} {
   set i [expr $i*$value]
}
set i
=> 111546435
					

It is also common to use a list-valued variable or command result instead of a static ...

Get Practical Programming in Tcl & Tk, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.