I think johngg has the "x" stuff nailed! I thought I'd show you a more Perl way to code this without 3 for(;;) loops, actually not any.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.