Controlling Loops

With both while and for loops, the tests at the top are there to stop the loop when some sort of condition has been reached. And, in many loops, it'll be the test that stops the loop. When you start working with more complex loops, however, or play with infinite loops as I have in some of the previous examples we've looked at, chances are good there will be some point in the middle of a loop block where you might want to stop looping, stop executing, or somehow control the actual execution of the loop itself. That's where loop controls come in.

Loop controls are simple constructs that are used to change the flow of execution of a loop. You've already seen two of them: next and last, to restart the loop and to break out of it ...

Get Sams Teach Yourself Perl in 21 Days, Second 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.