在Perl中转置 [英] Transpose in perl
问题描述
我已经开始学习perl,并且喜欢尝试新事物.
I have started learning perl and like to try out new things.
我在文本处理中遇到了一些问题. 我有一些格式的文本,
I have some problem in text processing. I have some text of the form,
0 1 2 3 4 5 6 7 8 9 10
6 7 3 6 9 3 1 5 2 4 6
我想转置此文本.就像,我想使行成为列,而使列成为行.在perl中有办法做到这一点吗?
I want to transpose this text. Like, I want to make rows as columns ans columns as rows. Id there a way to do this in perl?
谢谢大家.
推荐答案
因此,此解决方案使用数组数组,每个嵌套数组 是一行数据.很简单,您遍历每个列中的列 行,并使用列将其推入另一个数组 index作为将值推送到的索引.这有效果 根据您的要求旋转数据.
So this solution uses an array-of-arrays, each nested array is a row of data. Very simply you loop over the columns in each row and push them onto another array-of-arrays using the column index as the index which to push the value onto. This has the effect of pivoting the data as you requested.
#!/usr/bin/env perl
my @rows = ();
my @transposed = ();
# This is each row in your table
push(@rows, [qw(0 1 2 3 4 5 6 7 8 9 10)]);
push(@rows, [qw(6 7 3 6 9 3 1 5 2 4 6)]);
for my $row (@rows) {
for my $column (0 .. $#{$row}) {
push(@{$transposed[$column]}, $row->[$column]);
}
}
for my $new_row (@transposed) {
for my $new_col (@{$new_row}) {
print $new_col, " ";
}
print "\n";
}
结果是:
0 6
1 7
2 3
3 6
4 9
5 3
6 1
7 5
8 2
9 4
10 6
这篇关于在Perl中转置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!