Perl Loops

Perl Loops

Perl Loops 150 150 Roderick Derks

Perl supports four main loop types:

  1. while

  2. for

  3. until

  4. foreach

In each case, the execution of the loop continues until the evaluation of the supplied expression changes.

  • In the case of a while loop execution continues while the expression evaluates to true.
  • The until loop executes while the loop expression is false and only stops when the expression evaluates to a true value.
  • The list forms of the for and foreach loop are special cases. They continue until the end of the supplied list is reached.

while Loops

The while loop has three forms:

while EXPRLABEL
while (EXPR) BLOCKLABEL
while (EXPR) BLOCK continue BLOCK

In first form, the expression is evaluated first, and then the statement to which it applies is evaluated. For example, the following line increases the value of $linecount as long as we continue to read lines from a given file:

For example, the following line increases the value of $linecount as long as we continue to read lines from a given file:

$linecount++ while ();

To create a loop that executes statements first, and then tests an expression, you need to combine while with a preceding do {} statement. For example:

do
{
$calc += ($fact*$ivalue);
} while $calc <100;

In this case, the code block is executed first, and the conditional expression is only evaluated at the end of each loop iteration.

The second two forms of the while loop repeatedly execute the code block as long as the result from the conditional expression is true. For example, you could rewrite the preceding example as:

while($calc < 100)
{
$calc += ($fact*$ivalue);
}

The continue block is executed immediately after the main block and is primarily used as a method for executing a given statement (or statements) for each iteration, irrespective of how the current iteration terminated. It is somehow equivalent to for loop

{
my $i = 0;
while ($i <100)
{ ... }
continue
{
$i++;
}
}

This is equivalent to
for (my $i = 0; $i < 100; $i++)
{ ... }

for Loops

A for loop is basically a while loop with an additional expression used to reevaluate the original conditional expression. The basic format is:

LABEL for (EXPR; EXPR; EXPR) BLOCK

The first EXPR is the initialization – the value of the variables before the loop starts iterating. The second is the expression to be executed for each iteration of the loop as a test. The third expression is executed for each iteration and should be a modifier for the loop variables.

Thus, you can write a loop to iterate 100 times like this:

for ($i=0;$i<100;$i++)
{
...
}

You can place multiple variables into the expressions using the standard list operator (the comma):

for ($i=0, $j=0;$i<100;$i++,$j++)

You can create an infinite loop like this:

for(;;)
{
...
}

until Loops

The inverse of the while loop is the until loop, which evaluates the conditional expression and reiterates over the loop only when the expression returns false. Once the expression returns true, the loop ends.

In the case of a do.until loop, the conditional expression is only evaluated at the end of the code block. In an until (EXPR) BLOCK loop, the expression is evaluated before the block executes. Using an until loop, you could rewrite the previous example as:

do
{
$calc += ($fact*$ivalue);
} until $calc >= 100;

This is equivalent to

do
{
$calc += ($fact*$ivalue);
} while $calc <100;

foreach Loops

The last loop type is the foreach loop, which has a format like this:

LABEL foreach VAR (LIST) BLOCK
LABEL foreach VAR (LIST) BLOCK continue BLOCK

Using a for loop, you can iterate through the list using:

for ($index=0;$index<=@months;$index++)
{
print "$months[$index]\n";
}

This is messy, because you.re manually selecting the individual elements from the array and using an additional variable, $index, to extract the information. Using a foreach loop, you can simplify the process:

foreach (@months)
{
print "$_\n";
}

The foreach loop can even be used to iterate through a hash, providing you return the list of values or keys from the hash as the list:

foreach $key (keys %monthstonum)
{
print "Month $monthstonum{$key} is $key\n";
}

Labled Loops

Labels can be applied to any block, but they make the most sense on loops. By giving your loop a name, you allow the loop control keywords to specify which loop their operation should be applied to. The format for a labeled loop is:

LABEL: loop (EXPR) BLOCK ...

For example, to label a for loop:

ITERATE: for (my $i=1; $i<100; $i++)
{
print "Count: $i\n";
}

Loop Control – next, last and redo

There are three loop control keywords: next, last, and redo.

The next keyword skips the remainder of the code block, forcing the loop to proceed to the next value in the loop. For example:

while (<DATA>)
{
next if /^#/;
}

Above code would skip lines from the file if they started with a hash symbol. If there is a continue block, it is executed before execution proceeds to the next iteration of the loop.

The last keyword ends the loop entirely, skipping the remaining statements in the code block, as well as dropping out of the loop. The last keyword is therefore identical to the break keyword in C and Shellscript. For example:

while ()
{
last if ($found);
}

Would exit the loop if the value of $found was true, whether the end of the file had actually been reached or not. The continue block is not executed.

The redo keyword reexecutes the code block without reevaluating the conditional statement for the loop. This skips the remainder of the code block and also the continue block before the main code block is reexecuted. For example, the following code would read the next line from a file if the current line terminates with a backslash:

while(<DATA>)
{
if (s#\\$#)
{
$_ .= <DATA>;
redo;
}
}

Here is an example showing how labels are used in inner and outer loops

OUTER:
while(<DATA>)
{
chomp;
@linearray=split;
foreach $word (@linearray)
{
next OUTER if ($word =~ /next/i)
}
}

goto Statement

There are three basic forms: goto LABEL, goto EXPR, and goto &NAME. In each case, execution is moved from the current location to the destination.

In the case of goto LABEL, execution stops at the current point and resumes at the point of the label specified.

The goto &NAME statement is more complex. It allows you to replace the currently executing subroutine with a call to the specified subroutine instead.

Roderick Derks

Liefhebber van fietsen, van het oplossen van IT puzzels, en van het delen van informatie om anderen te helpen.

All stories by:Roderick Derks

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Your Name (required)

    Your Email (required)

    Subject

    Your Message

      Your Name (required)

      Your Email (required)

      Subject

      Your Message