How can I partition a Perl array into equal sized chunks?

后端 未结 9 1469
眼角桃花
眼角桃花 2020-12-15 08:01

I have a fixed-sized array where the size of the array is always in factor of 3.

my @array = (\'foo\', \'bar\', \'qux\', \'foo1\', \'bar\', \'qux2\', 3, 4, 5         


        
9条回答
  •  情歌与酒
    2020-12-15 08:24

    Another generic solution, non-destructive to the original array:

    use Data::Dumper;
    
    sub partition {
        my ($arr, $N) = @_; 
    
        my @res;
        my $i = 0;
    
        while ($i + $N-1 <= $#$arr) {
            push @res, [@$arr[$i .. $i+$N-1]];
            $i += $N; 
        }   
    
        if ($i <= $#$arr) {
            push @res, [@$arr[$i .. $#$arr]];
        }   
        return \@res;
    }
    
    print Dumper partition(
        ['foo', 'bar', 'qux', 'foo1', 'bar', 'qux2', 3, 4, 5], 
        3   
    );
    

    The output:

    $VAR1 = [
              [
                'foo',
                'bar',
                'qux'
              ],
              [
                'foo1',
                'bar',
                'qux2'
              ],
              [
                3,
                4,
                5
              ]
            ];
    

提交回复
热议问题