简体   繁体   English

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

[英]Display array content in column dynamically using perl

I would like to display array contents in column view. 我想在列视图中显示数组内容。 For example: My array contains 9 values as below: 例如:我的数组包含9个值,如下所示:

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

I want display the values in 2 columns as below: 我想在2列中显示如下值:

One      Two
Three    Four
Five     Six
Seven    Eight
Nine

I can use tables and display as shown above but i want to do the same thing dynamically using loops for a very large array. 我可以使用如上所示的表和显示,但我想动态地使用循环来做一个非常大的数组。

Can anyone please help me with this. 任何人都可以帮我这个。

Thank You 谢谢

Avinesh Avinesh

Using splice, you can also modify number of columns: 使用拼接,您还可以修改列数:

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";
}

A simple math trick would also do this. 一个简单的数学技巧也可以做到这一点。 Check if the array index is divisible by 2. If yes, print a newline as long as it is not the 0th element. 检查数组索引是否可以被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";
}

If you want something printable instead of tabs, 如果你想要一些可打印的东西而不是标签,

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;

You should harness the power of CPAN , use the module Data::Tabulator . 您应该利用CPAN的强大功能,使用模块Data :: Tabulator It does exactly what you need, "Create a table (two-dimensional array) from a list (one-dimensional array)" . 它完全符合您的需要, “从列表(一维数组)创建一个表(二维数组)”

You can also use map : 你也可以使用map

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

or: 要么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM