25.6. Control Structures

Like other languages, Perl supports many different control structures that can be used to execute particular blocks of code based on decisions or repeat blocks of code while a particular condition is true. The following sections cover the various control structures available in Perl.

25.6.1. While and Until

The while loop executes one or more lines of code while a specified expression remains true. The while loop has the following syntax:

while (<expression>) {
  # statement(s) to execute
}

Because the <expression> is evaluated at the beginning of the loop, the statement(s) will not be executed if the <expression> is false at the beginning of the loop. For example, the following loop will execute 20 times, each iteration of the loop incrementing x until it reaches 20:

my $x = 0;
while ($x <= 20) {  # do until $x = 20 (will not execute when x = 21)
  $x++;  # increment x
}

The until loop is similar to the while loop except that the loop is executed until the expression is false:

until (<expression>) {
  # statement(s) to execute while expression is true
}

25.6.2. For

The for loop executes statement(s) a specific number of times and is governed by two expressions and a condition:

for (<initial_value>; <condition>; <loop_expression>) {
  # statement(s) to execute
}

The <initial_value> expression is evaluated at the beginning of the loop; this event occurs only before the first iteration of the loop. The <condition> is evaluated at the beginning of each loop iteration. ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.