in reply to Re^6: array in different columns
in thread array in different columns

Try

#!perl use strict; my @array = qw( -- 0.0175 0.0483 0.0507 -- 0.0471 0.0483 -- 0.0287 --); my @column; my $curr_column = 0; my $rows = 0; while (@array) { if( $array[0] ne '--' ) { push @{ $column[ $curr_column ] }, shift @array; if( $rows < $#{ $column[ $curr_column ] } ) { $rows = $#{ $column[ $curr_column ] }; }; } else { $curr_column++; $column[ $curr_column] ||= [0]; # a new column shift @array; }; }; for my $row (0..$rows) { my @tmp = (); for (@column){ if ( exists ($_->[ $row - $rows -1 ]) ){ push @tmp,$_->[ $row - $rows - 1 ]; } } print join "\t", @tmp; print "\n"; };
poj

Replies are listed 'Best First'.
Re^8: array in different columns
by Muflone82 (Novice) on Nov 23, 2016 at 13:52 UTC
    PERFECT! Among my array I insert at the start of the code:
    chomp @array
    because I have the newline. Thank you to everybody! ...if you want can you explain me the code?...
      The previous post by poj prints:
      0 0.0175 0 0.0483 0.0471 0 0.0507 0.0483 0.0287 0
      I don't see anywhere in your spec where these extra zeroes are required or even desired!
      Please be very specific about the requirements.

      I recommend something like this:

      #!/usr/bin/perl use strict; use warnings; my @array = qw( -- 0.0175 0.0483 0.0507 -- 0.0471 0.0483 -- 0.0287 --); my @twod_array; my $i_col = -1; my $i_row; foreach my $ele (@array) { if ($ele eq '--') { $i_col++; #new column starts $i_row = $i_col; next; } $twod_array[$i_row++][$i_col] = $ele; } foreach my $row_ref (@twod_array) { print join ("\t",@$row_ref),"\n"; } __END__ 0.0175 0.0483 0.0471 0.0507 0.0483 0.0287