The “ForEach” loop easily iterates all values in an array or hash, and takes the form:
ForEach variable in [reversed] arrayOrHash v1.1
code to repeat (aka: the loop's body)
End
The loop’s body will be run exactly once for each value in the array, or key in the hash. For an array the values are visited in order starting with index zero. The optional keyword reversed allows visiting the values in the array from last to first. Each time the loop body is executed the value of the variable is updated automatically.
The “ForEach” loop also has a few variants that can provide more information about the current loop value. If looping over an array, you may provide two variables. The first will be set to the index of the value in the array, and the second to the value itself, eg:
ForEach $index, $value in $myArray
This extended ForEach construct can also be used with hashes, in one of the following ways:
ForEach $key, $value in $myHash
ForEach $index, $key, $value in $myHash
Note on mutation: changes to the array are seen while the loop is in progress. However, if the array grows in size, elements added to the end are not visited. If the array shrinks in size, an out-of-bounds index error will occur.
If you modify the set of defined hash keys while the loop is in progress, the changes will not be seen by the loop (eg: the old keys will be visited, not the new ones). However, any changes to hash values are seen.
Previous Chapter For Loop |
<< index >> |
Next Chapter For Each with Ranges |