Perl: the Markov chain saw | |
PerlMonks |
Re: Perl Best Practices - Loop Labelsby haj (Vicar) |
on Apr 16, 2020 at 22:24 UTC ( [id://11115658]=note: print w/replies, xml ) | Need Help?? |
Short version: I'm strictly following PBP on this one, and I agree with your current usage. I'm following my own shortcut rule to this: Always use labels after next, redo, and last.. That includes: Use labels even if the loop isn't nested. Maybe it will become nested when some other guy adds some feature years later, and for that case the label adds robustness. When refactoring complex loops it helps to define the scope: Extracting an inner loop into a subroutine needs extra care if the inner loop contains a last OUTER;. It has already been noted by others that good names for labels also make good documentation - next FILE; or last TRY; tell pretty well what the line is trying to achieve, and I don't need to scroll even if that line happens to be at the top of my screen. I don't see these loop controls related to goto, but rather to two other mechanisms of execution control: return and die. A return is implicitly labeled with the surrounding sub (I know, special cases exist where it isn't), and die is followed by a description why you bail out. With a label, loop control keywords achieve the same level of self-explanation. Loop control, returning from a subroutine and exceptions are part of every modern programming language, and they have in common that they go strictly "upward" in the call stack or loop hierarchy. A goto LABEL; or even, horrors, goto EXPRESSION is indeed scary, not only for maintenance of the code, but also for those who write compilers and interpreters.
In Section
Seekers of Perl Wisdom
|
|