Loop Controls

As you’ve surely noticed by now, Perl is one of the so-called structured programming languages. In particular, there’s just one entrance to any block of code, 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 one 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 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. For 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. Of course, that comment line at the end is merely a comment—it’s not required in any way. We just threw that in to make it clearer what’s happening.

There are five kinds of loop blocks in Perl. These are the blocks of for, foreach, while, until, or the naked block.[*] The curly braces of an if block or subroutine[] don’t qualify. As you may have noticed in the example above, the last operator applied to the entire loop block. ...

Get Learning Perl, 5th 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.