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, when, while, or until, for example:

  • expr1 if expr2 ;

  • expr1 foreach list ;

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

  • 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 loop block without evaluating the conditional again. Skips the continue block.

When blocks

when blocks can be used within a topicalizer to form a switch statement. Topicalizers are foreach (or for), and given:

for ( expr ) {
  [ when ( condition ) block . . . ]
  [ default block ]
}

given ( expr ) { . . . }

condition testing is done using smartmatching, see page 35. The first condition that matches will have its block executed, and control transfers to the end of the topicalizer block. default is a when that always matches.

In a when block, continue can be used to transfer control to the next statement instead of skipping to the end of the topicalizer block.

In a given block, break can be used to force leaving the topicalizer block.

Note that given is a relatively new feature and several aspects of its peculiar behavior may change in subsequent Perl releases.

Special forms

  • do block while expr ;

  • do block until expr ;

Guaranteed to perform block once before testing expr.

  • do block

Effectively turns block into an expression.

...

The placeholder ... (ellipsis) can be used as a statement to indicate code that is not yet written. It compiles, but throws an exception when executed.

perlsyn.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset