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.
- MillerIn reply to Re: Pivoting 2 dimensional array refs
by wind
in thread Transposing 2 dimensional arrays
by Voronich
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |