Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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

by ctilmes (Vicar)
on May 09, 2016 at 13:58 UTC ( [id://1162547]=note: print w/replies, xml ) Need Help??


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

Several good ways to do this have already been mentioned for Perl 5.

I'll also note that your question was one of the many things addressed in Perl6.

Perl 6 added an explicit phaser for first loop invocation you can use like this:

for @arr -> $line { FIRST { print ' ' xx $indentation }; say $line; }

Replies are listed 'Best First'.
Re^2: Easiest way to do something only on first iteration of loop
by ibm1620 (Hermit) on May 09, 2016 at 14:43 UTC
    I only realized now that all of the above solutions have the condition backward: the first time through the loop I don't want to print an indentation. An outer routine has already typed a "header", like a number or a bullet, to the left and the print-head is now positioned at the indentation column at the time the subroutine is called. The first line must be printed without further indentation, but any subsequent lines will need indentation.

    Interestingly, it was only when reading the Perl 6 syntax that this leaped out at me. For my purpose I'd need the NEXT phaser rather than the FIRST phaser. Thanks for the tip.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-19 22:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found