Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I break an outer loop from an inner one in Perl?

Tags:

Suppose I have a piece of Perl code like:

foreach my $x (@x) {  foreach my $y (@z) {   foreach my $z (@z) {    if (something()) {     # I want to break free!    }    # do stuff    }   # do stuff  }  # do stuff } 

If something() is true, I would like to break ('last') all the loops.

how can I do that? I thought of two options, both of which I don't like: Using something GOTO Adding a boolean variable which will mark something() is true, check this var in each of the loops before they resume and last() if it's true.

Any suggestions or thoughts?

Thanks.

like image 474
David B Avatar asked Sep 14 '10 11:09

David B


People also ask

How do you break the outer for loop from the inner loop?

Java break and Nested Loop In the case of nested loops, the break statement terminates the innermost loop. Here, the break statement terminates the innermost while loop, and control jumps to the outer loop.

How do I break a nested loop in Perl?

If you want to exit a nested loop, put a label in the outer loop and pass label to the last statement. If LABEL is specified with last statement, execution drops out of the loop encountering LABEL instead of currently enclosing loop.

How do you break out of a loop in Perl?

In many programming languages you use the break operator to break out of a loop like this, but in Perl you use the last operator to break out of a loop, like this: last; While using the Perl last operator instead of the usual break operator seems a little unusual, it can make for some readable code, as we'll see next.


1 Answers

Use a label:

OUTER: foreach my $x (@x) {  foreach my $y (@z) {   foreach my $z (@z) {    if (something()) {     last OUTER;    }    # do stuff    }   # do stuff  }  # do stuff } 
like image 131
Wooble Avatar answered Oct 02 '22 13:10

Wooble