Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: How do I loop through a list two or more elements at a time?

by jeroenes (Priest)
on Oct 24, 2001 at 15:37 UTC ( #121081=note: print w/replies, xml ) Need Help??


in reply to How do I loop through a list two or more elements at a time?

For a real answer now: create your list as an array of arrays, loop on the outer array.
print "$_->[0] - $_->[1]\n" for @LoL;

If you start with a flat list, you create the LoL with davorg's solution:

my @LoL; while(my @items = splice( @list, 0, 2) ){ push @LoL, [@items]; }
or non-destructive:
my $size = 2; die "Uneven list" if @list % $size; my @LoL; for my $index ( 0.. $#list ){ my $rem = $index % $size; $LoL[($index - $rem)/$size]->[$rem] = $list[$index]; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2021-10-28 20:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (96 votes). Check out past polls.

    Notices?