在 perl 中转置 [英] Transpose in perl

查看:35
本文介绍了在 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 "
";
}

这导致:

0 6 
1 7 
2 3 
3 6 
4 9 
5 3 
6 1 
7 5 
8 2 
9 4 
10 6

这篇关于在 perl 中转置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆