如何以块的形式打印数组并指定每行要打印的元素数量?
#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
谢谢!
答案 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)
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__