foreach(n) Tcl Built-In Commands foreach(n) _________________________________________________________________ NNAAMMEE foreach - Iterate over all elements in one or more lists SSYYNNOOPPSSIISS ffoorreeaacchh _v_a_r_n_a_m_e _l_i_s_t _b_o_d_y ffoorreeaacchh _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 _________________________________________________________________ DDEESSCCRRIIPPTTIIOONN The ffoorreeaacchh command implements a loop where the loop vari­ able(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), ffoorreeaacchh assigns the contents of the element to _v_a_r_n_a_m_e as if the lliinnddeexx com­ mand 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 asso­ ciated 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 vari­ ables 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 variables in each iteration, empty values are used for the missing elements. The bbrreeaakk and ccoonnttiinnuuee statements may be invoked inside _b_o_d_y, with the same effect as in the ffoorr command. FFoorreeaacchh returns an empty string. EEXXAAMMPPLLEESS The following loop uses i and j as loop variables to iter­ ate 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. 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. SSEEEE AALLSSOO for(n), while(n), break(n), continue(n) KKEEYYWWOORRDDSS foreach, iteration, list, looping Tcl foreach(n)