![]() |
|
"be consistent" | |
PerlMonks |
Re: Perl style question: loops with postconditionby Anonymous Monk |
on Jun 28, 2002 at 19:40 UTC ( [id://178116]=note: print w/replies, xml ) | Need Help?? |
My viewpoint is to use as high-level a construct as is posible. High-level constucts: for(;;), foreach(), while(), do{}while() are easily recognized and the reader can concentrate on what the loop does. Use lower level constructs when the high-level constructs don't give you what you need. for(), foreach() and while() satisfy 99% of my needs, and I rarely use any of the forms you list. do{}while() is appealing because it runs at least once, so it seems useful when a loop needs an initialization. However, things are rarely that simple, and usually the first pass will be quite difference, especially once you provide handling for NULL input: an empty array, an undef array, no such file, etc. So I wind up refactoring some of the code into a subroutine and using an ordinary loop, perhaps with some initialization. The 'last if/unless $condition' form is usefull when you need to exist in the middle of a loop. while(){}continue{} is good, if it can isolate the actions which follow the condition detection point, but that doesn't always work, and sometimes there are two or more related conditions, eg: file does not exist, file is not readable, file is empty, end of file. As an aside, sometimes I have wound up with this form when, during development, I want to do some debugging after the condition point, which gets removed prior to the final release. Rather than re-work the whole loop, the clumsier code gets left behind. Other than the form used in AUTOLOAD routines, GOTO is hardly ever needed. Since it is clumsy and reveals nothing about the intention of the jump, it is best to avoid GOTO unless there is no other way to do what you want. Very rarely, using loop and condition constructs becomes so clumsy that using a GOTO allows the rest to be simplified greatly. Most of the time, a last, next or redo can do the job ... they are simply synonyms for GOTO with more information about the intent. I don't think I've used a GOTO since packing away my TRS-80, but I have seen code that called for it. TomDLux
In Section
Seekers of Perl Wisdom
|
|