Description: Iterate over all elements in one or more lists
Syntax: foreach varname list body
foreach varlist1 list1 ?varlist2 list2 ...? body
Argument: variable name, a list of variable, command body
Returns: empty string
See Also: While, for, break, continue
Examples:
#The following
loop uses i and j as loop variables to iterate over #pairs of
elements of a single list.
set x
{}
foreach {i j} {a
b c d e f} {
lappend x $j
$i
}
SETVAL
text1=$x
# The value of x
and tag text1 is "b a d c f e"
# There are 3
iterations of the loop.
The next loop
uses i and j to iterate over two lists in parallel.
set x
{}
foreach i {a b c}
j {d e f g} {
lappend x $i
$j
}
SETVAL
text1=$x
# The value of x
and text1 is " a d b e c f {} "
# There are 4
iterations of the loop.
The two forms are
combined in the following example.
set x
{}
foreach i {a b c}
{j k} {d e f g} {
lappend x $i $j
$k
SETVAL
text1=$x
}
# The value of x
and text1 is " a d e b f g c { "
# There are 3
iterations of the loop.
The foreach command implements a loop where the loop variable takes on values from a list.
Usually there is one loop variable, varname, and one list, which is a set of values to assign to varname. There can be multiple lists and list variables used by the command.
Hint The list is recommended to build the list using lappend or similar command. Use lindex to test your list.
The body argument is a Tcl script. For each element of list (in order from first to last), foreach assigns the contents of the element to varname, then calls the Tcl interpreter to execute body.
To use more than one list (e.g., list1, list2) each list can be associated with a loop variable (e.g., varlist1 and varlist2). During each iteration, the loop variables of each varlist are assigned from the corresponding list.
Values in each list are used once in order from first to last. The number of loop iterations depends on the number of elements in the list.
If using multiple lists, if a value list does not contain enough elements for each of its loop variables in each iteration, empty values are used for the missing elements.
The break and continue statements may be invoked inside body, with the same effect as in the for command. Foreach returns an empty string.