24

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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
David B
  • 29,258
  • 50
  • 133
  • 186

2 Answers2

46

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
}
Wooble
  • 87,717
  • 12
  • 108
  • 131
16

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

Dave Cross
  • 68,119
  • 3
  • 51
  • 97