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

Re: loop thru 3-element array?

by Limbic~Region (Chancellor)
on Sep 27, 2004 at 23:43 UTC ( [id://394407]=note: print w/replies, xml ) Need Help??


in reply to loop thru 3-element array?

anadem,
Perl6 is going to make this a lot easier :-)
I have been fascinated with iterators lately, so this mildly tested code can easily be changed to iterate by any quantity specified.
#!/usr/bin/perl use strict; use warnings; my @array = 0 .. 30; my $next = by_groups_of( 3, @array ); while ( my @group = $next->() ) { print "@group\n"; } sub by_groups_of { my $by = shift; return sub { () } if ! $by || $by =~ /\D/ || ! @_; my @list = @_; # Make a copy in case it changes my $end = $#list; my $pos = 0; my $done; return sub { return () if $done; my $stop = $pos + $by - 1 > $end ? $end : $pos + $by - 1; my @sub = @list[ $pos .. $stop ]; $pos += $by - 1; $done = 1 if $stop == $end; return @sub; } }

Cheers - L~R

Update: Also see this node if you need to have modifications to the looping variables modify the array as well

Replies are listed 'Best First'.
Re^2: loop thru 3-element array?
by kelan (Deacon) on Sep 28, 2004 at 14:23 UTC

    Since you're making a separate copy of the list that gets passed in anyway, you could also use the splice trick that merlyn showed above, and get rid of all the arithmetic.

    sub by_groups_of { my $by = shift; return sub { () } if ! $by || $by =~ /\D/ || ! @_; my @list = @_; # here's the copy. we're safe to splice return sub { splice @list, 0, $by }; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-25 19:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found