简体   繁体   中英

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:

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

I want display the values in 2 columns as below:

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

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.

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 . It does exactly what you need, "Create a table (two-dimensional array) from a list (one-dimensional array)" .

You can also use map :

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

or:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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