如何将 Perl 数组划分为大小相等的块? [英] How can I partition a Perl array into equal sized chunks?
本文介绍了如何将 Perl 数组划分为大小相等的块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个固定大小的数组,其中数组的大小始终是 3 的因数.
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);
如何对数组的成员进行聚类,以便我们可以得到一个由 3 组组成的数组:
How can I cluster the member of array such that we can get an array of array group by 3:
$VAR = [ ['foo','bar','qux'],
['foo1','bar','qux2'],
[3, 4, 5] ];
推荐答案
my @VAR;
push @VAR, [ splice @array, 0, 3 ] while @array;
或者你可以使用 natatime
来自List::MoreUtils
or you could use natatime
from List::MoreUtils
use List::MoreUtils qw(natatime);
my @VAR;
{
my $iter = natatime 3, @array;
while( my @tmp = $iter->() ){
push @VAR, \@tmp;
}
}
这篇关于如何将 Perl 数组划分为大小相等的块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文