foreach
Iterates over a list and sets variable to be each element of list, performing BLOCK for each element of list.
Format
foreach unit [arg] variable (list) {BLOCK}
Parameters
Parameter | Definition |
---|---|
unit | controls how list is split into individual elements
Default |
arg | optional context information for the unit; currently only used with __single and __multi |
variable | name of the element that is equated to each element in list |
list | list that contains one or more elements that can be equated to variable |
BLOCK | one or more statements that are executed when variable has been equated to an element from list |
Description
The foreach loop iterates over list and sets variable to be each element of list, performing BLOCK for each element of list in turn.
It should be noted that the following are equivalent:
- foreach f ("<some list>") ....
- foreach line f ("<some list>") ....
- foreach __single "\n" f ("<some list>") ....
Similarly, the following are equivalent:
- foreach word f ("<some list>") ....
- foreach __multi " \t\n" f ("<some list>") ....
The arguments _multi and _single do not need to be literal strings; they can be variables. For example:
separators = ":|"; foreach __multi separators var ("::data1:data2:data3|data4::||:data5") {printf(">%s<\n", var);}
The following examples highlight the usage of the foreach statement.
Sum the elements in an array:
foreach elem ("1\n2\n3\n4\n5") {
sum += elem;
}
List the login ID of each account on the system:
print (ntharg(item, 1, ":"), "\n");
}
Count the number of words in a string:
foreach word w ("The cat sat on the mat."){
words++;
}
Example of the __single form of the foreach loop that reformats a list:
cleanList = "";
foreach __single ":|" var (dirtyList) {
if (cleanList) {
cleanList = cleanList . "-";
}
{if (var == "")
{var = "<empty>";}
cleanList = cleanList . var;
}
printf("%s\n", cleanList);
Example of the __multi form of the foreach loop that reformats a list:
cleanList = "";
foreach __multi ":|" var (dirtyList) {
if (cleanList) {
cleanList = cleanList . "-";
}
cleanList = cleanList . var;
}
printf("%s\n", cleanList);
Where to go from here