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.
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With