Loop Controls

Perl is one of the “structured” programming languages. In particular, there’s one entrance to any block of code, which is at the top of that block. But there are times when you may need more control or versatility than what we’ve shown so far. For example, you may need to make a loop like a while loop but that always runs at least once. Or maybe you need to occasionally exit a block of code early. Perl has three loop-control operators you can use in loop blocks to make the loop do all sorts of tricks.

The last Operator

The last operator immediately ends the execution of the loop. (If you’ve used the “break” operator in C or a similar language, it’s like that.) It’s the “emergency exit” for loop blocks. When you hit last, the loop is done as in this example:

    # Print all input lines mentioning fred, until the _ _END_ _ marker
    while (<STDIN>) {
      if (/_ _END_ _/) {
        # No more input on or after this marker line
        last;
      } elsif (/fred/) {
        print;
      }
    }
    ## last comes here ##

Once an input line has the _ _END_ _ marker, that loop is done. The comment line at the end is not required, but we threw it in to clarify what’s happening.

The five kinds of loop blocks in Perl are for, foreach, while, until, and the naked block.[248] The curly braces of an if block or subroutine[249] don’t qualify. In the example above, the last operator applied to the entire loop block.

The last operator will apply to the innermost currently running loop block. To jump out of outer blocks, stay tuned; that’s coming ...

Get Learning Perl, Fourth Edition 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.