问题
I have an array like this
@array = (
1,
some 9-digit number-1,
some 9-digit number-2,
2,
some 9-digit number-3,
some 9-digit number-4
.....and so on
);
Now I want to print this in a table as
1 some 9-digit number-1 some 9-digit number-2
2 some 9-digit number-3 some 9-digit number-4
3 some 9-digit number-5 some 9-digit number-6
I also want to print the table to a text file. What logic would be the best ?
Thanks
回答1:
I figured it out. I used Text::Table Thanks – John F
use Text::Table;
my $tb = Text::Table->new( "Heading 1", "Heading 2" , "Heading 3");
for (my $i = 0; $i <= $#array; $i += 3) {
$tb->load([@array[$i, $i+1, $i+2]]);
}
print $tb;
回答2:
A module isn't really necessary for this simple task.
Here's an alternative solution that just uses splice and printf.
use strict;
use warnings;
my @array = (
1, 999999991, 999999992,
2, 999999993, 999999994,
3, 999999995, 999999996,
);
while ( @array >= 3 ) {
printf "%-4s %-10s %s\n", splice @array, 0, 3;
}
output
1 999999991 999999992
2 999999993 999999994
3 999999995 999999996
来源:https://stackoverflow.com/questions/25209959/perl-how-to-create-table-from-an-array