Breaking out of loops

You can break out of loops using next, last and similar statements.

#!/usr/bin/perl -w

LINE: while (<STDIN>) {
        chomp;                        # remove newline
        next LINE if $_ eq '';        # skip blank lines
        last LINE if lc($_) eq 'q';   # quit
}

The LINE indicating the block to break out of is optional (it defaults to the current smallest loop), but can be very useful when you wish to break out of a loop higher up the chain:

#!/usr/bin/perl -w

LINE: while (<STDIN>) {
        chomp;                                   # remove newline
        next LINE if $_ eq '';                   # skip blank lines

        # we split the line into words and check all of them
        foreach (split $_) {
                last LINE if lc($_) eq 'quit';   # quit
        }
}