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

泄露秘密 提交于 2019-12-21 03:28:06

问题


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.


回答1:


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
}



回答2:


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



来源:https://stackoverflow.com/questions/3708527/how-do-i-break-an-outer-loop-from-an-inner-one-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!