A while loop is a very flexible construct, but it can be clumsy. It refers to a mechanism: a code block repeated until some condition drops from true to false. The Foreach statement is a shortcut looping construct which makes more sense for list and hash data types.
Often you would like to apply to each element of a list the sequence of instructions in a code block. For instance, to print out the element, or, to categorize the element and increment a count of the number of such elements on the list.
In principal you can set this up as a while loop. But the foreach statement does all the work and gives a nice, intuitive package. It has syntax:
[keyword foreach] [a scalar variable to catch the Next value] [a list of values]
The list of values is enclosed in parentheses. It is often a list, in which case the variable will begin with an at-sign.
» Try the example code in the window and see what it does.
The block of code controlled by the foreach statement is run once on each element of the list. A copy of the (scalar) value at each location of the list, in turn, is placed into the named scalar in the statement, in this case $code, and the block run with this assignment. This is repeated for each element of the list, in turn, and then the code moves on the the following statements. If the list is empty, no problem, the block of code is never run.
» Modify the program to count the number of adenine nucleotides in dna_sequence. You will put in if statement into the body of the foreach loop.
Beware! Do not compare strings using ==, use "eq", as in $code eq 'a'.
This is where the discussion goes. It's a long box underneath both the other boxes.