Is there any Perl equivalent for php's array_chunk()?
I'm trying to divide a large array into several smaller ones.
Thanks in advance.
Is there any Perl equivalent for php's array_chunk()?
I'm trying to divide a large array into several smaller ones.
Thanks in advance.
You can use array slices like this:
#!/bin/perl -l
my @array = (1,2,3,4,5,6,7,8,9);
print join ",", @array[0..2];
print join ",", @array[3..5];
print join ",", @array[6..$#array];
To match the php fuction you can use a number of approaches:
use strict;
use warnings;
use List::MoreUtils qw( natatime part );
use Data::Dumper;
my @array = 0..9;
my $size = 3;
{ my $i = 0;
my @part = part { int( $i++ / $size ) } @array;
warn "PART\n";
warn Dumper \@part;
}
{ my $iter = natatime( $size, @array );
my @natatime;
while( my @chunk = $iter->() ) {
push @natatime, \@chunk;
}
warn "NATATIME\n";
warn Dumper \@natatime;
}
{ my @manual;
my $i = 0;
for( 0..$#array ) {
my $row = int( $_ / $size );
$manual[$row] = []
unless exists $manual[$row];
push @{$manual[$row]}, $array[$_];
}
warn "MANUAL:\n";
warn Dumper \@manual;
}
One of the easier ways is to use List::MoreUtils
and either the natatime
or part
functions.
With natatime, it creates an iterator, so this might not be what you want:
my $iter = natatime 3, @orig_list;
And every call to $iter->()
returns 3 items in the list.
Then there's part
.
my $i = 0;
my @groups = part { int( $i++ / 3 ) } @orig_array;
If you want to make this easier, you can write your own function: chunk_array
.
sub chunk_array {
my $size = shift;
my $i = 0;
return part { int( $i++ / $size ) } @_;
}
And you would call it as simple as:
my @trios = chunk_array( 3, @orig_array );