Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display array content in column dynamically using perl

Tags:

arrays

loops

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

like image 943
Avinesh Kumar Avatar asked Dec 03 '22 00:12

Avinesh Kumar


2 Answers

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";
}
like image 156
perreal Avatar answered Dec 21 '22 22:12

perreal


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";
}
like image 32
Bee Avatar answered Dec 21 '22 22:12

Bee