foreach(n) Tcl Built-In Commands foreach(n) _________________________________________________________________ NAME foreach - Iterate over all elements in one or more lists SYNOPSIS foreach _v_a_r_n_a_m_e _l_i_s_t _b_o_d_y foreach _v_a_r_l_i_s_t_1 _l_i_s_t_1 ?_v_a_r_l_i_s_t_2 _l_i_s_t_2 ...? _b_o_d_y _________________________________________________________________ DESCRIPTION The foreach command implements a loop where the loop variable(s) take on values from one or more lists. In the simplest case there is one loop variable, _v_a_r_n_a_m_e, and one list, _l_i_s_t, that is a list of values to assign to _v_a_r_n_a_m_e. The _b_o_d_y argument is a Tcl script. For each element of _l_i_s_t (in order from first to last), foreach assigns the contents of the element to _v_a_r_n_a_m_e as if the lindex command had been used to extract the element, then calls the Tcl interpreter to execute _b_o_d_y. In the general case there can be more than one value list (e.g., _l_i_s_t_1 and _l_i_s_t_2), and each value list can be associ- ated with a list of loop variables (e.g., _v_a_r_l_i_s_t_1 and _v_a_r_- _l_i_s_t_2). During each iteration of the loop the variables of each _v_a_r_l_i_s_t are assigned consecutive values from the corresponding _l_i_s_t. Values in each _l_i_s_t are used in order from first to last, and each value is used exactly once. The total number of loop iterations is large enough to use up all the values from all the value lists. If a value list does not contain enough elements for each of its loop vari- ables in each iteration, empty values are used for the miss- ing elements. The break and continue statements may be invoked inside _b_o_d_y, with the same effect as in the for command. Foreach returns an empty string. 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 } # The value of x is "b a d c f e" # There are 3 iterations of the loop. Tcl Last change: 1 foreach(n) Tcl Built-In Commands foreach(n) 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 } # The value of x is "a d b e c f {} g" # 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 } # The value of x is "a d e b f g c {} {}" # There are 3 iterations of the loop. KEYWORDS foreach, iteration, list, looping Tcl Last change: 2