Looping with foreach
The foreach
command implements a loop with the variable or variables assigned values from one or more lists and then performs an action. The list or lists may be pre-existing or created as part of the command. This command allows us to perform actions on a list or list of values with minimal effort.
How to do it…
In the following recipe, we will create a Tcl script, to be called from the command line, that recreates the previous recipe by providing hard coded values.
Create a text file named foreach.tcl
that contains the following commands.
# First we create a list containing the values to print set numbers {1 2 3 4 5 6 7 8 9 10} foreach x $numbers { puts "x = $x" }
Now invoke the script using the following command line:
% tclsh85 foreach.tcl x = 1 x = 2 x = 3 x = 4 x = 5 x = 6 x = 7 x = 8 x = 9 x = 10
How it works…
The action was invoked a total of 10 times as in the previous example. However, as we provided a list to be used, there was no computation required. This is exceptionally...