Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: getting iteration number inside iteration loop

by ferreira (Chaplain)
on Jun 29, 2007 at 14:47 UTC ( #624095=note: print w/replies, xml ) Need Help??


in reply to getting iteration number inside iteration loop

You may get this behavior with List::MoreUtils. The following presents two such solutions. They are not very pretty, but they work.

First, you may generate an index array with [ 0 .. $#array ] and use each_arrayref/each_array to produce an iterator that loops over possibly many arrays at a time.

use List::MoreUtils qw( each_arrayref ); my @a = qw( a b c d e ); my $each = each_arrayref( [ 0..$#a ], \@a ); while ( my ($idx, $v) = $each->() ) { print "$idx: $v\n"; }
Second, you may use the documented behavior that the iterator returns the current index when given arguments ('index').
use List::MoreUtils qw( each_array ); my @a = qw( a b c d e ); my $each = each_array( @a ); while ( my $v = $each->() ) { my $idx = $each->('index'); print "$idx: $v\n"; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2018-09-20 07:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Eventually, "covfefe" will come to mean:













    Results (173 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!