Menu

PERL TUTORIALS - Perl Loops

Perl Loops

ADVERTISEMENTS

Loop TypeDescription
while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
until loopRepeats a statement or group of statements until a given condition becomes true. It tests the condition before executing the loop body.
for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
foreach loopThe foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn.
do...while loopLike a while statement, except that it tests the condition at the end of the loop body
nested loopsYou can use one or more loop inside any another while, for or do..while loop.

ADVERTISEMENTS

Loop Control Statements:

Control StatementDescription
next statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
last statementTerminates the loop statement and transfers execution to the statement immediately following the loop.
continue statementA continue BLOCK, it is always executed just before the conditional is about to be evaluated again.
redo statementThe redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed.
goto statementPerl supports a goto command with three forms: goto label, goto expr, and goto &name.

ADVERTISEMENTS

The Infinite Loop:

#!/usr/local/bin/perl
 
for( ; ; )
{
   printf "This loop will run forever.\n";
}