in reply to how to seperate array after a certain number of elements?
And the output is:#!/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); } }
Update: Tighter codeC:\Code>perl close_and_break.pl 1 2 3 4 5 6 7 8 9 10 11 12
|
|---|
| 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 |