3

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.

4 Answers 4

15

splice() function.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. It really helped. Moving from php to perl is not an easy job :)
@Antonio: Not an easy job, but it really worth it ! :)
Why is it not an easy job?
Examine List::MoreUtils for their implementation of n-at-a-time (natatime) function which uses splice and an anonymous function
8

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];

Comments

3

To match the PHP function 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;
}

Comments

2

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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.