We don't bite newbies here... much | |
PerlMonks |
Re: Easiest way to do something only on first iteration of loopby GrandFather (Saint) |
on May 07, 2016 at 22:39 UTC ( [id://1162450]=note: print w/replies, xml ) | Need Help?? |
It depends on context. Sometimes the flag approach in some guise is the cleanest solution. Often hoisting the first time code out of the loop is clearer, but may need thinking about the loop contents differently. A frequent pattern is where some first time initialisation is needed as in a loop that finds minimum and maximum values. If that just depends on the first element of an array you can easily do that outside the loop and then skip the first element in the loop:
Where you are really handling several phases of processing it is clearer to use a loop for each phase. A first loop to skip over initial stuff from a file that isn't interesting for example, then a second loop to process the interesting bit. Even where you have special case code in the loop, often you don't need a flag variable. Just make use of undef handling. For example:
If you have specific examples, show us and we'll do what we can to help.
Premature optimization is the root of all job security
In Section
Seekers of Perl Wisdom
|
|