如何使用Perl以块的形式处理和打印数组?

时间:2010-12-24 15:22:52

标签: arrays perl

如何以块的形式打印数组并指定每行要打印的元素数量?

#Given    
@array = qw/a b c d e f g i j/;
$chr_per_line =3;

输出:

a b c \n
d e f \n
g i j \n

谢谢!

6 个答案:

答案 0 :(得分:6)

我不喜欢使用破坏性的splice来做这类事情,而是使用来自List::MoreUtils

natatime(一次只有N个)
use List::MoreUtils 'natatime';

my @array = qw/a b c d e f g i j/;
my $iter = natatime 3, @array;

while( my @chunk = $iter->() ) { 
    print join( ' ', @chunk ), "\n";
}

答案 1 :(得分:4)

使用splice

while (@array) {
    print join " ", splice(@array, 0, $chr_per_line), "\n";
}

答案 2 :(得分:3)

这是我在模块List::Gen

中解决的众多列表任务之一
use List::Gen 'every';

my @array = qw(a b c d e f g h i);

print "@$_\n" for every 3 => @array;

打印:

a b c
d e f
g h i

natatime不同,此处的切片仍为源列表别名:

$$_[0] = uc $$_[0] for every 3 => @array;

print "@array\n"; # 'A b c D e f G h i'

答案 3 :(得分:2)

List::MoreUtils::natatime

use strict;
use warnings;
use List::MoreUtils qw(natatime);

my @array = qw/a b c d e f g i j/;
my $it = natatime(3, @array);
while (my @vals = $it->()) {
    print "@vals\n";
}

__END__
a b c
d e f
g i j

答案 4 :(得分:2)

拼接解决方案也可以写成:

while ( my @chunk = splice(@array, 0, $chr_per_line) ) {
    print join( ' ', @chunk, "\n" );
}

如果您需要在循环中执行多项操作,则可以更方便。

答案 5 :(得分:0)

这也有效

use strict;  
use warnings;   

my @array = qw/a b c d e f g i j/;  
my $chr_per_line =3;  

for (my ($i,$k)=(0,0); ($k+=$chr_per_line)<=@array; $i=$k) {  
   print "@array[$i .. $k-1] \n";  
}    

__END__