Transpose in perl

前端 未结 9 1729
一向
一向 2020-12-09 18:41

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条回答
  •  Happy的楠姐
    2020-12-09 19:17

    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";
    }
    

    This results in:

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

提交回复
热议问题