Initial version of donated sources by Avertec, 3.4p5.
[tas-yagle.git] / distrib / share / tcl / help / tcl / control / foreach
1 NAME
2 foreach - Iterate over all elements in one or more lists
3
4 SYNOPSIS
5 foreach varname list body
6 foreach varlist1 list1 ?varlist2 list2 ...? body
7
8
9 DESCRIPTION
10 The foreach command implements a loop where the loop variable(s) take
11 on values from one or more lists. In the simplest case there is one
12 loop variable, varname, and one list, list, that is a list of values to
13 assign to varname. The body argument is a Tcl script. For each ele-
14 ment of list (in order from first to last), foreach assigns the con-
15 tents of the element to varname as if the lindex command had been used
16 to extract the element, then calls the Tcl interpreter to execute body.
17
18 In the general case there can be more than one value list (e.g., list1
19 and list2), and each value list can be associated with a list of loop
20 variables (e.g., varlist1 and varlist2). During each iteration of the
21 loop the variables of each varlist are assigned consecutive values from
22 the corresponding list. Values in each list are used in order from
23 first to last, and each value is used exactly once. The total number
24 of loop iterations is large enough to use up all the values from all
25 the value lists. If a value list does not contain enough elements for
26 each of its loop variables in each iteration, empty values are used for
27 the missing elements.
28
29 The break and continue statements may be invoked inside body, with the
30 same effect as in the for command. Foreach returns an empty string.
31
32 EXAMPLES
33 The following loop uses i and j as loop variables to iterate over pairs
34 of elements of a single list.
35
36 set x {}
37 foreach {i j} {a b c d e f} {
38 lappend x $j $i
39 }
40 # The value of x is "b a d c f e"
41 # There are 3 iterations of the loop.
42
43
44 The next loop uses i and j to iterate over two lists in parallel.
45
46 set x {}
47 foreach i {a b c} j {d e f g} {
48 lappend x $i $j
49 }
50 # The value of x is "a d b e c f {} g"
51 # There are 4 iterations of the loop.
52
53
54 The two forms are combined in the following example.
55
56 set x {}
57 foreach i {a b c} {j k} {d e f g} {
58 lappend x $i $j $k
59 }
60 # The value of x is "a d e b f g c {} {}"
61 # There are 3 iterations of the loop.
62
63
64
65 SEE ALSO
66 for(n), while(n), break(n), continue(n)
67
68
69 KEYWORDS