2011-08-28 64 views
5

我有一個未知數量的單詞數組,具有未知的最大長度。 我需要將其轉換爲另一個數組,基本上將其轉換爲列字數組。 所以用這種原始的數組:如何將單詞數組轉換爲包含單詞字符的數組?

@original_array = ("first", "base", "Thelongest12", "justAWORD4"); 

的resluting陣列將是:

@result_array = ("fbTj","iahu","rses","selt","t oA"," nW"," gO"," eR"," sD"," t4"," 1 "," 2 "); 

其實我都會有這樣的:

fbTj 
iahu 
rses 
selt 
t oA 
    nW 
    gO 
    eR 
    sD 
    t4 
    1 
    2 

我需要做的是,爲了使表,這些詞是表格的標題。 我希望我已經表達清楚,並感謝您願意給予的幫助。

我與分割功能嘗試過,但我一直搞亂起來......

編輯: 大家好,感謝所有的提示和建議!我從大家那裏學到了很多東西,因此得到了讚賞。然而,我發現tchrist的答案更方便,也許是因爲我來自c,c#背景...... :)

回答

5

我有一個老程序可以做到這一點。也許你能適應它:

$ cat /tmp/a 
first 
base 
Thelongest12 
justAWORD4 

$ rot90 /tmp/a 
fbTj 
iahu 
rses 
selt 
t oA 
    nW 
    gO 
    eR 
    sD 
    t4 
    1 
    2 

這裏的源:

$ cat ~/scripts/rot90 
#!/usr/bin/perl 
# rot90 - [email protected] 

$/ = ''; 

# uncomment for easier to read, but not reversible: 
### @ARGV = map { "fmt -20 $_ |" } @ARGV; 

while (<>) { 
    chomp; 
    @lines = split /\n/; 
    $MAXCOLS = -1; 
    for (@lines) { $MAXCOLS = length if $MAXCOLS < length; } 
    @vlines = (" " x @lines) x $MAXCOLS; 
    for ($row = 0; $row < @lines; $row++) { 
     for ($col = 0; $col < $MAXCOLS; $col++) { 
      $char = (length($lines[$row]) > $col ) 
        ? substr($lines[$row], $col, 1) 
        : ' '; 
      substr($vlines[$col], $row, 1) = $char; 
     } 
    } 
    for (@vlines) { 
     # uncomment for easier to read, but again not reversible 
     ### s/(.)/$1 /g; 
     print $_, "\n"; 
    } 
    print "\n"; 
} 
7
use strict; 
use warnings; 
use 5.010; 
use Algorithm::Loops 'MapCarU'; 

my @original_array = ("first", "base", "Thelongest12", "justAWORD4"); 
my @result_array = MapCarU { join '', map $_//' ', @_ } map [split //], @original_array; 
+0

+1對於功能性方法,像往常一樣最簡潔 – daxim

1
use strict; 
use warnings; 
use List::Util qw(max); 

my @original_array = ("first", "base", "Thelongest12", "justAWORD4"); 
my @new_array = transpose(@original_array); 

sub transpose { 
    my @a = map { [ split // ] } @_; 
    my $max = max(map $#$_, @a); 
    my @out; 
    for my $n (0 .. $max) { 
     $out[$n] .= defined $a[$_][$n] ? $a[$_][$n] : ' ' for 0 .. $#a; 
    } 
    return @out; 
} 
0

可以通過這個簡單的一行容易實現:

perl -le'@l=map{chomp;$m=length if$m<length;$_}<>;for$i(0..$m-1){print map substr($_,$i,1)||" ",@l}' 
相關問題