in reply to how to seperate array after a certain number of elements?

There is no built-in function, but I can give an example. Since you might need to break on different values, this is one place a solution based on a closure might be apt:

#!/usr/bin/perl use warnings; use strict; my @data = ( 1,2,3,4,5,6,7,8,9,10,11,12 ); my @collection = (); my $break_5 = &break_by(5); $break_5->( \@data, \@collection ); for my $c (@collection) { print $_, " " for @{$c}; print "\n"; } sub break_by { my $count = shift; return sub { my ( $data_ref, $collection_ref ) = @_; my @temp = (); foreach (@{$data_ref}) { push @temp, $_; if ( @temp >= $count ) { push @{$collection_ref}, [@temp]; @temp = (); } } push @{$collection_ref}, [@temp] if (@temp); } }
And the output is:

C:\Code>perl close_and_break.pl 1 2 3 4 5 6 7 8 9 10 11 12
Update: Tighter code

Replies are listed 'Best First'.
Re^2: how to seperate array after a certain number of elements?
by ikegami (Patriarch) on Sep 20, 2007 at 20:24 UTC
    Or you could go a step further and make an iterator.
    sub break_by { my ($by, $data) = @_; my $i = 0; return sub { my $n = @$data - $i; $n = $n < 0 ? 0 : $n > $by ? $by : $n; $i += $n; return @$data[$i-$n..$i-1]; } } my @data = ( 1,2,3,4,5,6,7,8,9,10,11,12 ); my $iter = break_by(5, \@data); while (my @group = $iter->()) { print("@group\n"); }