PERL : How to create table from an array?

坚强是说给别人听的谎言 提交于 2020-01-04 09:05:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!