in reply to Transposing 2 dimensional arrays
Here's my version that's a little more perlish as you'd say.:
use Data::Dumper; use strict; use warnings; sub pivot { my @src = @_; my $max_col = 0; $max_col < $#$_ and $max_col = $#$_ for @src; my @dest; for my $col (0..$max_col) { my @new_row; for my $row (0..$#src) { push @new_row, $src[$row][$col] // ''; } push @dest, \@new_row; } return @dest; } my @test = ( [1..5], [11..15], [21..25], [31..35], [41], [51..55], ); my @results = pivot(@test); print Dumper(\@results); =prints $VAR1 = [ [1,11,21,31,41,51], [2,12,22,32,'',52], [3,13,23,33,'',53], [4,14,24,34,'',54], [5,15,25,35,'',55] ]; =cut
Update: And a little more perlish still would be to use map:
sub pivot { my @src = @_; my $max_col = 0; $max_col < $#$_ and $max_col = $#$_ for @src; my @dest; for my $col (0..$max_col) { push @dest, [map {$src[$_][$col] // ''} (0..$#src)]; } return @dest; }
This last is actually my preferred way of doing this, since it's easy to see what the inner loop is iterating on.
- Miller
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Pivoting 2 dimensional array refs
by choroba (Cardinal) on May 13, 2011 at 08:38 UTC | |
|
Re^2: Pivoting 2 dimensional array refs
by John M. Dlugosz (Monsignor) on May 14, 2011 at 10:53 UTC | |
by Voronich (Hermit) on May 14, 2011 at 14:11 UTC | |
by John M. Dlugosz (Monsignor) on May 14, 2011 at 15:43 UTC | |
by Voronich (Hermit) on May 18, 2011 at 15:32 UTC | |
by John M. Dlugosz (Monsignor) on May 18, 2011 at 19:02 UTC | |
by BrowserUk (Patriarch) on May 14, 2011 at 14:24 UTC | |
by Voronich (Hermit) on May 14, 2011 at 16:41 UTC | |
by Anonymous Monk on May 14, 2011 at 14:31 UTC | |
|
Re^2: Pivoting 2 dimensional array refs
by Voronich (Hermit) on May 13, 2011 at 13:07 UTC |