Perl并排打印两个独立阵列的内容

时间:2017-11-24 01:33:04

标签: arrays perl

我有兴趣将两个数组的内容并排打印而不是一个接一个地打印出来。

我的阵列是:

my @present = ("John", "Mary", "Jimmy", "Kumar", "Ling");
my @absent = ("Joanne", "Charlotte", "Mei");

这是输出的样子:

Present    Absent    
=======    ======
John       Joanne
Mary       Charlotte
Jimmy      Mei
Kumar
Ling

使用Text :: Table查看示例似乎表明内容是逐行打印的。有没有一种方法逐列打印内容?

2 个答案:

答案 0 :(得分:2)

您可以重新构建数据,以便可以使用Text :: Table。 它还识别ANSI颜色转义,例如

但对于这个简单的情况,这很好用。 (根据您的数据,在计算字符串长度之前不要忘记解码utf8)

use strict;
use warnings;
use 5.010;
use List::Util qw / max /;
my @present = qw/ John Mary Jimmy Kumar Ling /;
my @absent = qw/ Joanne Charlotte Mei /;
my @columns = (\@present, \@absent);
my @headers = qw/ Present Absent /;
my @width;

for my $i (0 .. $#headers) {
    unshift @{ $columns[ $i ] }, '=' x length $headers[ $i ];
    unshift @{ $columns[ $i ] }, $headers[ $i ];
    $width[ $i ] = max map { length } @{ $columns[ $i ] };
}

my $rows = max map { $#$_ } @columns;
for my $i (0 .. $rows ) {
    my $fmt = join '   ', map { '%-' . $width[ $_ ] . 's' } 0 .. $#headers;
    my @col = map { $columns[ $_ ]->[ $i ] // '' } 0 ..$#headers;
    printf "$fmt\n", @col;
}

答案 1 :(得分:1)

这些代码可以帮助您:

#!/usr/local/bin/perl
use strict;
use warnings;
my $format = "%-10s\t%-10s\n";
my @present = ("John", "Mary", "Jimmy", "Kumar", "Ling");
my @absent = ("Joanne", "Charlotte", "Mei");
my $maxrows = $#present > $#absent ?  $#present : $#absent; 
printf($format,"Present","Absent");
printf($format,"=======","======");
for my $rownum ( 0..$maxrows ) { 
    printf ( $format, $present[$rownum] // '', $absent[$rownum] // '' );

    }

输出:

Present     Absent    
=======     ======    
John        Joanne    
Mary        Charlotte 
Jimmy       Mei       
Kumar                 
Ling