Chapter 11. Statements

A statement is an expression, optionally followed by a modifier, and terminated with a semicolon. Statements can be combined to form a block when enclosed in {}. The semicolon may be omitted after the last statement of a block.

Execution of expressions can depend on other expressions using one of the modifiers if, unless, for, foreach, while, or until, for example:

  • expr1 if expr2 ;

  • expr1 foreach list ;

The operators ||, &&, or ?: also allow conditional execution, for example:

  • expr1 || expr2 ;

  • expr1 ? expr2 : expr3 ;

Blocks may be used for conditional execution:

  • if (expr) block [ [ elsif (expr) block . . .] else block ]

  • unless (expr) block [ else block ]

Loop blocks:

  • [ label: ] while (expr) block [ continue block ]

  • [ label: ] until (expr) block [ continue block ]

  • [ label: ] for ( [ expr ] ; [ expr ] ; [ expr ] ) block

  • [ label: ] foreach var(list) block [ continue block ]

  • [ label: ] block [ continue block ]

In foreach, the iteration variable (default $_) is aliased to each element of the list, so modifying this variable modifies the actual list element.

The keywords for and foreach can be used interchangeably.

In loop blocks, program flow can be controlled with:

goto label

Finds the statement labeled with label and resumes execution there. label may be an expression that evaluates to the name of a label.

last [ label ]

Immediately exits the loop. Skips the continue block.

next [ label ]

Executes the continue block and starts the next iteration of the loop.

redo [ label ]

Restarts the ...

Get Perl Pocket Reference, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.