4

我想在列视图中显示数组内容。例如:我的数组包含 9 个值,如下所示:

@numbers = ("One","Two","Three","Four","Five","Six","Seven","Eight","Nine");

我想在 2 列中显示值,如下所示:

One      Two
Three    Four
Five     Six
Seven    Eight
Nine

我可以使用表格和显示如上所示,但我想动态地使用循环对一个非常大的数组做同样的事情。

谁能帮我解决这个问题。

谢谢你

阿维内什

4

5 回答 5

10

使用拼接,您还可以修改列数:

use strict;
use warnings;

my @numbers = ("One","Two","Three","Four","Five","Six","Seven","Eight","Nine");
my $numcols = 2;
while (@numbers) {
  print join("\t", splice(@numbers,0, $numcols)), "\n";
}
于 2012-12-13T06:19:38.437 回答
5

一个简单的数学技巧也可以做到这一点。检查数组索引是否可被 2 整除。如果是,则打印一个换行符,只要它不是第 0 个元素。

my @numbers = ("One","Two","Three","Four","Five","Six","Seven","Eight","Nine");

foreach my $i (0..$#numbers) {
  print "\n" if ($i%2 == 0 and $i != 0);
  print $numbers[$i] . "\t";
}
于 2012-12-13T08:38:16.037 回答
1

如果你想要一些可打印的东西而不是标签,

push @data, '' if @data % 2 != 0;

my $col1_width = 0;
my $col2_width = 0;
for (my $i=0; $i<@data; ) {
   $col1_width = length($data[$i]) if length($data[$i]) > $col1_width; ++$i;
   $col2_width = length($data[$i]) if length($data[$i]) > $col2_width; ++$i;
}

my $format = "%-${col1_width}s  %-${col2_width}s\n";
printf($format, splice(@data, 0, 2))
   while @data;
于 2012-12-13T08:10:31.200 回答
1

您应该利用CPAN的力量,使用模块Data::Tabulator。它完全符合您的需要,“从列表(一维数组)创建一个表(二维数组)”

于 2012-12-13T11:49:11.510 回答
0

您还可以使用地图

map { print $numbers[$_] . ( ($_ + 1) % $numcols == 0 ? "\n" : "\t" ) } 0..$#numbers;

或者:

@numbers = map { $numbers[$_] . ( ($_ + 1) % $numcols == 0 ? "\n" : "\t" ) } 0..$#numbers;
print @numbers;
于 2012-12-13T11:39:41.697 回答