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

后端 未结 9 1459
眼角桃花
眼角桃花 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:30

    Use the spart function from the List::NSect package on CPAN.

        perl -e '
        use List::NSect qw{spart};
        use Data::Dumper qw{Dumper};
        my @array = ("foo", "bar", "qux", "foo1", "bar", "qux2", 3, 4, 5);
        my $var = spart(3, @array);
        print Dumper $var;
        '
    
        $VAR1 = [
              [
                'foo',
                'bar',
                'qux'
              ],
              [
                'foo1',
                'bar',
                'qux2'
              ],
              [
                3,
                4,
                5
              ]
            ];
    

提交回复
热议问题