in reply to Perl Best Practices - Loop Labels
The normal way (in my opinion) to exit completely from an inner and outer loop in C or Perl is to use a return statement. You put the loops in a subroutine and use an embedded return statement. Yes, there are some folks who advocate for adding a conditional flag like: while(...and !$end_flag){}, where inside the loop the code sets $end_flag=1 to end the loop. The theory behind that is that the code should only one way in and only one way out. However, I believe that if the code is short (<1/3-1/2 page), having an intermediate "return" is no big deal. This is often an ERROR return and will have some sort of #ERROR comment.
In your pseudo code, there appears to be some assumption that going back to the outer loop somehow maintains the inner loop vars. I said "WHAT?". Perhaps you have a relatively short example that you could post and the Monks could have a go at it? I didn't understand completely the intent of your pseudo code.sub XXX { #sub setup params... for (...) { next if $cond1; for (...) { ... last if $cond2; # next OUTER if $cond2 ... last if $cond3; # next OUTER if $cond3; # WHAT? # INNER vars do not remain the same ... return() if $cond4; # same as last OUTER ... next if $cond5; # redundant all cndx are next ... } return if $condx6; #early return } return }
In general, the loop conditional should express the conditions upon which the loop normally terminates.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl Best Practices - Loop Labels
by kcott (Archbishop) on Apr 16, 2020 at 08:47 UTC | |
by Marshall (Canon) on Apr 18, 2020 at 04:52 UTC |