Use a negative width to left-justify. For example,
"%5s" means pad to 5 characters, right-justified.
"%-5s" means pad to 5 characters, left-justified.

The following are not the most compact solutions, but they are probably the most readable. Don't forget that programs should be written for those who maintain them.

Untransposed:

use strict; use warnings; use List::Util qw( max ); use POSIX qw( ceil ); my @a = qw(un deux trois quatre jedan dva tritcheteri one two three); my $cols = 4; my $width = (max map length, @a) + 1; my $rows = ceil(@a / $cols); for my $r (0..$rows-1) { for my $c (0..$cols-1) { next if (my $i = $r * $cols + $c) > $#a; printf('%-*s', $width, $a[$i]); } print("\n"); }

Transposed:

use strict; use warnings; use List::Util qw( max ); use POSIX qw( ceil ); my @a = qw(un deux trois quatre jedan dva tritcheteri one two three); my $cols = 3; my $width = (max map length, @a) + 1; my $rows = ceil(@a / $cols); for my $r (0..$rows-1) { for my $c (0..$cols-1) { next if (my $i = $r + $c * $rows) > $#a; printf('%-*s', $width, $a[$i]); } print("\n"); }

Now, wouldn't it be nice if each column was as narrow as possible? There's gotta be a module to do that on CPAN, but I didn't find one quickly.

Update: I had to leave before I could finish writting my entire node. Here's the rest.

Update: Fixed a bug in "Transposed". Thanks to jhourcle for pointing it out.


In reply to Re: Printing an array columnwise or rowwise by ikegami
in thread Printing an array columnwise or rowwise by logen

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.