Loop control in Perl is very easy, like most languages, but the syntax does differ slightly from what a lot of languages use. There are a number of ways to control execution inside of a loop but the two most common are next and last.
next: Begins the next iteration of the loop without executing anything that follows. (The C analogy to this is continue -- be careful because continue has a completely different effect in perl).
last: End execution of the loop immediately.
There are other ways to break and otherwise affect loop control in perl, but they are not commonly used (see the perldoc notes in the citation for more details). Below are a few primitive examples of using next and last.
1 2 3 4 5 6 7 8 9 |
# Here we loop through an array and jump to the next iteration # if the string is not what we are searching for foreach my $item(@my_array){ print "String is " . $item. "\n"; if ($item eq "skip"){ next; } # code here will only execute for non "skip" items } |
1 2 3 4 5 6 7 8 |
# This code example searches an array for an item. # There is no reason to continue searching once the item has been found. foreach my $item(@my_array){ if ($item == $desired_item){ print "Found item!"; last; } } |




