Arrays 如何使用Perl以块的形式处理和打印数组?
如何将数组分块打印并指定每行打印多少个元素Arrays 如何使用Perl以块的形式处理和打印数组?,arrays,perl,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 谢谢 使用: 使用: 对于这类事情,我宁愿使用natatime(一次N个),而不是使用破坏性的拼接 对于这类事情,我宁愿使用natatime(一次N个),而不是使用破坏性的拼接 这是我在模块中提到的许多列表任务之一 其中打印: a b c d e f g h i
#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
谢谢 使用:
使用:
对于这类事情,我宁愿使用
natatime
(一次N个),而不是使用破坏性的拼接
对于这类事情,我宁愿使用
natatime
(一次N个),而不是使用破坏性的拼接
这是我在模块中提到的许多列表任务之一 其中打印:
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'
这是我在模块中提到的许多列表任务之一 其中打印:
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'
拼接解决方案也可以写成:
while ( my @chunk = splice(@array, 0, $chr_per_line) ) {
print join( ' ', @chunk, "\n" );
}
如果您需要在循环中执行多个操作,则更方便。拼接解决方案也可以编写为:
while ( my @chunk = splice(@array, 0, $chr_per_line) ) {
print join( ' ', @chunk, "\n" );
}
如果你需要在循环中做不止一件事,这会更方便。这也适用
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__
使用严格;
使用警告;
my@array=qw/a b c d e f g i j/;
我的$chr\u每行=3;
对于(我的($i,$k)=(0,0);($k+=$chr\u每行)这同样有效
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__
使用严格;
使用警告;
my@array=qw/a b c d e f g i j/;
我的$chr\u每行=3;
对于(我的($i,$k)=(0,0);(每行$k+=$chr_)