Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Foreach Loops

by perlfan (Curate)
on Mar 15, 2005 at 19:40 UTC ( #439735=note: print w/replies, xml ) Need Help??


in reply to Foreach Loops

You can have a counter:
my $i = 0; foreach (@myarray) { # stuff goes here $i++; }
A slight improvement over holli's in that you can access the entire i-1 previous elements.

Replies are listed 'Best First'.
Re^2: Foreach Loops
by Roy Johnson (Monsignor) on Mar 15, 2005 at 22:09 UTC
    You should really put the counter increment in the continue block, though, in case of next or redo. Compare:
    my @arr = ('a'..'m'); my $i=0; foreach (@arr) { # stuff goes here next if $i%4 == 0; print "$i: $_\n"; } continue { ++$i } $i = 0; foreach (@arr) { # stuff goes here next if $i%4 == 0; print "$i: $_\n"; ++$i; }

    Caution: Contents may have been coded under pressure.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://439735]
help
Chatterbox?
[erix]: oh, I see... it's pretty obvious really
[choroba]: What do you mean by "anchors"?
[erix]: anchors
[erix]: I have figured it out. I actually constructed them correctly but used a faulty url *headdesk*
[erix]: ( you use anchors to jump to via a #-suffix to the url -- I am sure you know )

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2018-06-19 12:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?



    Results (113 votes). Check out past polls.

    Notices?