Perl Control Structures - Loops

Loops

In the following, label is an optional identifier terminated by a colon, and block is a sequence of one of more Perl statements surrounded by braces. All looping constructs except for the C-style for-loop can have a continue block that is executed after each iteration of the loop body, before the loop condition is evaluated again.

label for ( expr1 ; expr2 ; expr3 ) block

This is the so-called C-style for loop. The first expression is evaluated prior to the first loop iteration. The second expression is evaluated prior to each iteration and the loop is terminated if it evaluates to false. The third expression is evaluated after each iteration, prior to deciding whether to perform the next. This for loop is the only looping construct that can not have a continue block, but expr3 is functionally equivalent.

label for var ( list ) block label for var ( list ) block continue block label foreach var ( list ) block label foreach var ( list ) block continue block

In foreach, var is a scalar variable that defaults to $_ if omitted. For each element of list, var is aliased to the element, and the loop body is executed once. The keywords for and foreach are synonyms and are always interchangeable.

label while ( expr ) block label while ( expr ) block continue block label until ( expr ) block label until ( expr ) block continue block

The while loop repeatedly executes the loop body as long as the controlling expression is true. The condition is evaluated before the loop body. until is similar, but executes the loop body as long as the condition is false.

label block label block continue block

The label block construct is a bit of an oddity: Perl treats a bare block – with or without a label – as a loop that is executed once. This means that the loop control keywords can be used to restart the block or to exit it prematurely; a bare block can also have a continue block.

Read more about this topic:  Perl Control Structures

Famous quotes containing the word loops:

    An accurate charting of the American woman’s progress through history might look more like a corkscrew tilted slightly to one side, its loops inching closer to the line of freedom with the passage of time—but like a mathematical curve approaching infinity, never touching its goal. . . . Each time, the spiral turns her back just short of the finish line.
    Susan Faludi (20th century)

    In the labyrinth of a difficult text, we find unmarked forks in the path, detours, blind alleys, loops that deliver us back to our point of entry, and finally the monster who whispers an unintelligible truth in our ears.
    Mason Cooley (b. 1927)