使用perl动态显示列中的数组内容

时间:2012-12-13 06:15:25

标签: arrays perl loops

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

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

我希望在2列中显示如下值:

One      Two
Three    Four
Five     Six
Seven    Eight
Nine

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

任何人都可以帮助我。

谢谢

Avinesh

5 个答案:

答案 0 :(得分: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";
}

答案 1 :(得分:3)

一个简单的数学技巧也可以做到这一点。检查数组索引是否可以被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";
}

答案 2 :(得分: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;

答案 3 :(得分:1)

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

答案 4 :(得分:0)

您还可以使用地图

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

或:

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