in reply to Re^2: array in different columns
in thread array in different columns
Maybe you want to think of it in a different way, by looking at how to divide the array across columns. If you build your columns and then print every row of your column, you should get your result. I'm going to first show you how to do it for a fixed number of columns and then how to expand that to an arbitrary number of columns:
my @column1; my @column2; my @column3; my @column4; while( @array and $array[0] ne '--') { push @column1, shift @array; }; shift @array; while( @array and $array[0] ne '--') { push @column2, shift @array; }; shift @array; while( @array and $array[0] ne '--') { push @column3, shift @array; }; shift @array; while( @array and $array[0] ne '--') { push @column4, shift @array; }; shift @array; for my $row (1..3) { print join "\t", $column1[$row], $column2[$row],$column3[$row],$co +lumn4[$row]; print "\n"; };
Now, that only works for four columns. To make it work with any number of columns, we need to move away from the named column arrays and store all column arrays in another array ("AoA"):
my @column; my $curr_column = 0; my $rows = 0; while( @array and ) { if( $array[0] ne '--' ) { $column[ $curr_column ] ||= []; # a new column push @{ $column[ $curr_column ] }, shift @array; if( $rows < $#{ $column[ $curr_column ] } ) { $rows = $#{ $column[ $curr_column ] }; }; } else { $index++; shift @array; }; }; for my $row (0..$rows) { print join "\t", map { $_->[ $row ] } @column; print "\n"; };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: array in different columns
by Muflone82 (Novice) on Nov 23, 2016 at 11:08 UTC | |
by Corion (Patriarch) on Nov 23, 2016 at 11:31 UTC | |
by Muflone82 (Novice) on Nov 23, 2016 at 11:52 UTC | |
by poj (Abbot) on Nov 23, 2016 at 13:36 UTC | |
by Muflone82 (Novice) on Nov 23, 2016 at 13:52 UTC | |
|