简体   繁体   中英

How can I divide a Perl array into smaller arrays?

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.

splice()函数。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM