Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Easiest way to do something only on first iteration of loop

by GrandFather (Saint)
on May 07, 2016 at 22:39 UTC ( [id://1162450]=note: print w/replies, xml ) Need Help??


in reply to Easiest way to do something only on first iteration of loop

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:

my $min = $values[0]; my $max = $values[0]; for my $value (@values[1 .. $#values]) { $min = $value if $value < $min; $max = $value if $value > $max ; }

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:

my $firstMatchline; while (<DATA>) { next if !conditionMet($_); $firstMatchline //= $.; ... }

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1162450]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2024-04-26 07:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found