None


How to Break Out of a for/while Loop in Perl

(0 votes, average 0 out of 5)

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;
     }
}

 

Partner Links:
 
Related Articles

» For Loops in Python

For loops in Python are a bit different than most languages.  You may not iterate over some integer and increment as you go.  Rather, python uses for loops to iterate over lists or strings (represented as lists).  Python also does not use brackets to determine scope, but rather indentation.  Example below.  123>>> x = [1, 2, 3]>>> for value in x: #begin for loop, note the colon>>> print x #part of the loop, indented in In some cases, you want to know the where in...

» How to Add or Switch a Display in Windows 7

In order to connect a laptop or desktop to a television (or use a two-monitor display), Windows 7 must be configured to output to a different source or multiple sources.  Here's how to do it:Connect your computer and display device(s) to be hooked up.  Open the Start menu and navigate to the Control Panel.If both display devices are connected, you should see two displays show in the Display window.  Activate both monitors and change if you would like the displays mirrored (both...

» Block Comments in Perl

Like many scripting languages, there is no real way to do block comments in Perl.  The proper way to do a block comment is simply to comment out each line with a # along the left side, and in fact many popular text editors such as vim and emacs facilitiate this behavior (we have a tutorial on how to do it in emacs ).There is an easier way to make the compiler ignore a block of code if you are interested in a less visibly-obvious solution.  This is great for short-term solutions but it...