在perl中转置

jer*_*ygo 14 perl matrix

我已经开始学习perl并喜欢尝试新事物.

我在文本处理方面遇到了一些问题.我有一些表格的文字,

0 1 2 3 4 5 6 7 8 9 10

6 7 3 6 9 3 1 5 2 4 6
Run Code Online (Sandbox Code Playgroud)

我想转置这个文本.就像,我想将行作为列和列作为行.我有办法在perl中这样做吗?

谢谢你们.

dal*_*ton 13

所以这个解决方案使用数组数组,每个嵌套数组都是一行数据.很简单,你循环遍历每一行中的列,并使用列索引作为将值推送到的索引将它们推送到另一个数组数组.这具有按您的请求旋转数据的效果.

#!/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";
}
Run Code Online (Sandbox Code Playgroud)

这导致:

0 6 
1 7 
2 3 
3 6 
4 9 
5 3 
6 1 
7 5 
8 2 
9 4 
10 6
Run Code Online (Sandbox Code Playgroud)


FMc*_*FMc 5

以下是转置数据的一种方法概述.通过这个例子将是有益的,因为你需要使用CPAN,你将学习有用的List::UtilList::MoreUtils模块,你将学习复杂数据结构的基础知识(参见perlreftut,perldscperllol),你将使用一个Perl中的迭代器.

use strict;
use warnings;
use List::MoreUtils qw(each_arrayref);

my @raw_data = (
    '0 1 2 3 4 5 6 7 8 9 10',
    '6 7 3 6 9 3 1 5 2 4 6',
);

my @rows = ... ; # Look up map() and split() to fill in the rest.
                 # You want an array of arrays.

my @transposed;  # You will build this in the loop below.

my $iter = each_arrayref(@rows);  # See List::MoreUtils documentation.

while ( my @tuple = $iter->() ){
    # Do stuff here to build up @transposed, which
    # will also be an array of arrays.
}
Run Code Online (Sandbox Code Playgroud)