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

3

26

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.

Endres answered 14/9, 2010 at 11:45 Comment(1)
In Perl, the comment token is spelled #, not //.Voluntarism
C
48

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
}
Ciera answered 14/9, 2010 at 11:47 Comment(0)
W
16

The "last LABEL" syntax is described in the documentation.

Whitleywhitlock answered 14/9, 2010 at 11:51 Comment(0)
D
-1

Note that you can also do this in a one liner. Use the keyword LINE. e.g. perl -ane 'next if length$F[5]!=1; for(split/,/,$F[6]){next LINE if length$_!=1}; print'

Dr answered 30/10, 2023 at 16:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.