Easy Tutorial
❮ Perl Intro Perl Goto Statement ❯

Perl Loops

Sometimes, we may need to execute the same block of code multiple times. Normally, statements are executed sequentially: the first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

Loop statements allow us to execute a statement or group of statements multiple times. Below is the flowchart for loop statements in most programming languages:

>

Note that the number 0, the string '0', "", an empty list (), and undef are false, while all other values are true. Using ! or not before true returns false.

Perl provides the following types of loops:

Loop Type Description
while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
until loop Repeats a statement or group of statements until a given condition becomes true. It tests the condition before executing the loop body.
for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
foreach loop The foreach loop iterates over a list or collection variable's values.
do...while loop Similar to the while statement, except that it tests the condition at the end of the loop body.
nested loops You can use one or more loops within any while, for, or do..while loop.

Loop Control Statements

Loop control statements change the execution sequence of the code, allowing you to jump to different parts of the code.

Perl provides the following loop control statements:

Control Statement Description
next statement Stops the execution of statements from the next statement to the end of the loop body, then goes to the continue block and returns to the start of the loop for the next iteration.
last statement Exits the loop block, thereby ending the loop.
continue statement The continue block is usually executed before the condition is evaluated again.
redo statement The redo statement restarts the loop at the first line of the current iteration, skipping any statements after redo and the continue block.
goto statement Perl has three forms of goto: goto LABEL, goto EXPR, and goto &NAME.

Infinite Loop

If the condition never becomes false, the loop will run indefinitely.

A for loop can traditionally be used to implement an infinite loop.

Since none of the three expressions that make up the loop are required, you can leave some conditional expressions empty to create an infinite loop.

Example

#!/usr/bin/perl

for( ; ; )
{
   printf "This loop will run forever.\n";
}

>

You can terminate the loop by pressing Ctrl + C.

When the condition expression is absent, it is assumed to be true. You can also set an initial value and an increment expression, but Perl programmers generally prefer to use the for(;;) structure to represent an infinite loop.

❮ Perl Intro Perl Goto Statement ❯