2014-02-19 46 views
0

我有一個2d perl數組,我想垂直打印每個數組,但是我不知道最大數組的大小。我將如何迭代矩陣?如何在perl中垂直打印2d陣列中的每個陣列

我@AoA =(
[ 「ABC」, 「DEF」,1,2,3],
[ 「等等」, 「blah2」,2],
[ 「你好」,「世界「,」如何「,」是「,」你「,」幹嘛?「,
);

期望的輸出:

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

+0

您已經改變了您所需要的輸出。那是故意的嗎? – Borodin

回答

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? 

這有點密集,難以閱讀。將這條線分成幾行(一行創建所有$i'元素的臨時數組,另一行將它們連接在一起,另一行用於打印結果),可以使其更易讀。

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?