如何在perl中垂直打印2d数组中的每个数组

时间:2014-02-19 20:04:06

标签: perl

  

我有一个2d perl数组,我想垂直打印每个数组,但是,我不知道>最大阵列的大小。我将如何遍历矩阵?

     

我的@AoA =(
  [“abc”,“def”,1,2,3],
  [“blah”,“blah2”,2],
  [“hello”,“world”,“how”,“are”,“you”,“doing?”],
  );

     

期望的输出:

     

abc blah hello
  def blah2 world
  1 2 how
  2 null are
  3 null you
  null null doing

2 个答案:

答案 0 :(得分:1)

最好的方法是扫描您的数据两次:首先确定列中的最大项目数和项目的最大宽度,然后实际显示数据。

该程序演示

use strict;
use warnings;

my @AoA = (
  ["abc", "def", 1, 2, 3],
  ["blah", "blah2", 2],    
  ["hello", "world", "how", "are", "you", "doing?"],
);

my $maxrow;
my $maxwidth;
for my $col (@AoA) {
  my $rows = $#$col;
  $maxrow = $rows unless $maxrow and $maxrow >= $rows;
  for my $item (@$col) {
    my $width = length $item;
    $maxwidth = $width unless $maxwidth and $maxwidth >= $width;
  }
}

for my $row (0 .. $maxrow) {
  my $line = join ' ', map sprintf('%-*s', $maxwidth, $_->[$row] // ''), @AoA;
  print $line, "\n";
}

<强>输出

abc    blah   hello 
def    blah2  world 
1      2      how   
2             are   
3             you   
              doing?

<强>更新

提供修改后的输出要容易得多,因为无需计算最大字段宽度。

use strict;
use warnings;

my @AoA = (
  ["abc", "def", 1, 2, 3],
  ["blah", "blah2", 2],    
  ["hello", "world", "how", "are", "you", "doing?"],
);

my $maxrow;
for my $col (@AoA) {
  $maxrow = $#$col unless $maxrow and $maxrow >= $#$col;
}

for my $row (0 .. $maxrow) {
  print join(' ', map $_->[$row] // 'null', @AoA), "\n";
}

<强>输出

abc blah hello
def blah2 world
1 2 how
2 null are
3 null you
null null doing?

答案 1 :(得分:0)

use List::Util qw(max);

# calculate length of longest sub-array
my $n = max map { scalar(@$_) } @AoA;

for (my $i = 0; $i < $n; ++$i) {
    # the inner map{} pulls the $i'th element of each array,
    # replacing it with 'null' if $i is beyond the end;
    # each piece is then joined together with a space inbetween

    print join(' ', map { $i < @$_ ? $_->[$i] : 'null' } @AoA) . "\n";
}

<强>输出

abc blah hello
def blah2 world
1 2 how
2 null are
3 null you
null null doing?

这种密集且难以阅读。通过将print行拆分为多行(一行创建所有$i个元素的临时数组,另一行将它们连接在一起,另一行打印,可以使其更具可读性结果)。