Looping

A loop is a way to repeat a program action multiple times. A very simple example is a countdown timer that performs a task (waiting for one second) 300 times before telling you that your egg is done boiling.

Looping constructs (also known as control structures) can be used to iterate a block of code as long as certain conditions apply, or while the code steps through (evaluates) a list of values, perhaps using that list as arguments.

Perl has four looping constructs: for, foreach, while, and until.

The for construct performs a statement (block of code) for a set of conditions defined as follows:

for (start condition; end condition; increment function) { statement(s)

The start condition is set at the beginning of the loop. Each time the loop is executed, the increment function is performed until the end condition is achieved. This looks much like the traditional for/next loop. The following code is an example of a for loop:

for ($i=1; $i<=10; $i++) { print "$i\n"

foreach

The foreach construct performs a statement block for each element in a list or array:

@names = ("alpha","bravo","charlie"); foreach $name (@names) {

print "$name sounding off!\n";

The loop variable ($name in the example) is not merely set to the value of the array elements; it is aliased to that element. That means if you modify the loop variable, you're actually modifying the array. If no loop array is specified, the Perl default variable $_ may be used:

@names = ("alpha","bravo","charlie"); foreach (@names) {

This syntax can be very convenient, but it can also lead to unreadable code. Give a thought to the poor person who'll be maintaining your code. (It will probably be you.)

Was this article helpful?

0 0

Post a comment