The foreach statement iterates through all of the members of a list or a table. The syntax is:
foreach <variable> (<list_or_table_name>) {statements}
When the foreach statement is used with a list, the variable stores the value of each member of the list every time the foreach statement loops. The members returned are in numerical order by their list indices.
The following script matches numbers from an input file and stores the values in a list. The foreach statement cycles through every value stored in the list. Each value is printed and added to a subtotal, which is also printed.
ASL Script (foreachlist_do.asl): data = list(); total = 0; START { rep(NUMBERS)|eol } NUMBERS { x:integer } do { data += x; } DEFAULT { ..eol } do { print("Failed match"); } EOF do { foreach i (data) { total = total + i; print("Number: ".i); print("Subtotal ".total); } } Input (foreachlist_do.txt): 2 4 8 Output: $ sm_adapter --file=foreachlist_do.txt foreachlist_do.asl Number: 2 Subtotal: 2 Number: 4 Subtotal: 6 Number: 8 Subtotal: 14 $
When the foreach statement is used with a table, the variable receives the keys to the members of the table. Tables have no inherent order.
The next script matches numbers and words from an input file and stores the values in a table. The foreach statement cycles through every key stored in the table. Each key is printed as well as the associated value. The order in which the members of the table are printed is not necessarily the order in which the members were added to the table.
ASL Script (foreachtable_do.asl): pop = table(); total = 0; START { rep(NUMBERS) } NUMBERS { count:integer animal:word eol } do { pop[animal] = count; } DEFAULT {..eol} do {print("Failed match");} EOF do { foreach w (pop) { print("Animal ".w); print("Number ".pop[w]); } } Input (foreachtable_do.txt): 2 cows 4 cats 6 dogs 8 chickens Output: $ sm_adapter --file=foreachtable_do.txt foreachtable_do.asl Animal chickens Number 8 Animal cows Number 2 Animal cats Number 4 Animal dogs Number 6 $