我有一个未知数量的单词数组,最大长度未知。 我需要将它转换为另一个数组,基本上把它变成一个列字数组。 所以使用这个原始数组:
@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#background ......:)
答案 0 :(得分: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;
答案 1 :(得分: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 - tchrist@perl.com
$/ = '';
# 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";
}
答案 2 :(得分: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;
}
答案 3 :(得分:0)
这可以通过这个简单的单线程轻松完成:
perl -le'@l=map{chomp;$m=length if$m<length;$_}<>;for$i(0..$m-1){print map substr($_,$i,1)||" ",@l}'