Table of Contents

A Premature End to your loop

A loop, by its nature, continues. If that didn't make sense, start reading this sentence again.

The old jokes are the best, aren't they?

The joke above is a loop. You continue re-reading the sentence until you realise I'm trying to be funny. Then you exit the loop. Or maybe somebody doesn't exit it. Whatever, loops always run until the expression they are testing returns false. In the case of the examples above, a false value is returned when all the elements of the array have been cycled through, and the loop ends.

If you want an everlasting loop, just test an condition you know will always be true:

while (1) {
        print "$x:  Did you know you can press CTRL-C to interrupt a perl program?\n";

Another way to exit a loop is a simple foreach over the elements, as we have seen. But if we don't know when we want to exit a loop? For example, suppose we want to print out a list of names but stop when we find one with a particular title? You are throwing a huge party, someone is allergic to vodka, and this person has drunk from the punch bowl despite being assured by someone holding two empty bottles of Absolut that he was just using the bottles to convey yet more orange juice into said punch bowl. So you need a doctor, and so you write a Perl script to find one from the list of attendees, wanting the doctor's name to be the last item printed:

@names=('Mrs Smith','Mr Jones','Ms Samuel','Dr Jansen','Sir Philip');

foreach $person (@names) {
	print "$person\n";
	last if $person=~/Dr /;

The last operator is our friend. Don't worry about the /Dr / business -- that is a regular expression which we cover next. All you need to know is that it returns true if the name begins with 'Dr '. When it does return true, last is operated and the loop ends early.