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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With