The for(;;) type loops can be a big source of "off by one" errors. Perl is great because often this is not necessary! Below I passed around references to the 2-D array, but that didn't add much complication to the code.
There are some limitations below, but I didn't see the need to go past the original code's capabilities. I think others have pointed out that there are modules like Text::Table, et al, but normally just adding enough space between columns in a print to cover 98 % case with one more space is enough (you don't want to run columns together so that they can't be parsed by another program, but one wacko line alignment per 20 pages won't throw the human reader off).
Have fun Perling!
#!/usr/bin/perl -w use strict; # transpose input. won't align right if rows don't have # same # num of things, but then again Op's version will go # pretty wacky with: 1 2 3 4 # a b c d e f my @inAoA; my @transposed_AoA; while (<DATA>) { chomp; #not needed for \s, but here for \t option push(@inAoA,[split(/\s/,$_)]); #could be \t too } transpose_2d_array(\@inAoA, \@transposed_AoA); dump_AoA (\@transposed_AoA); sub transpose_2d_array { my ($in_aref, $out_aref) = @_; foreach my $in_row (@$in_aref) { my $new_row =0; foreach my $col_ele (@$in_row) { push (@{$out_aref->[$new_row]},$col_ele); $new_row++; } } } sub dump_AoA #with tabs between columns { my $AoA_ref = shift; foreach my $aref (@$AoA_ref) { print join("\t",@$aref),"\n"; } } =PrintOut of above code: 1 a 2 b 3 c 4 d 5 e 6 f =cut __DATA__ 1 2 3 4 5 6 a b c d e f
In reply to Re: Transpose the contents of the file
by Marshall
in thread Transpose the contents of the file
by snape
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |