Secondly, I want the array printed or displayed in columns as "tight" as possible and _justified left_. I don't manage justifying left with sprintf(). Let's choose 4 columns. Knowing $max, the shortest I manage is:

Okay, let's assume we know $max (see ikegami's response) and $col:

use POSIX qw(ceil); my $rows = ceil( scalar @a / $col ); for ( my $i = 0; $i < $rows; $i++ ) { printf( ("%-${max}s " x $col)."\n", map { defined $_ ? $_ : '' } @a[($i*$col)..(($i*$col)+($col-1))] ); } # transposed $rows = ceil (scalar @a / $col ); for ( my $i = 0; $i < $rows; $i++ ) { printf( ("%-${max}s " x $col)."\n", map { defined $_ ? $_ : '' } @a[ map { $i+($_*$rows) } (0..$col-1) ] ); }

Of course -- it won't fill the width when transposed -- it fills height first. It'll also extend the end of your array, because of the way I'm messing with it, so you'll want to make a copy first (which isn't too bad if you're working in a subroutine)

Personally, I'd just like the '#' feature in MudOS's version of (s)printf (you tell it a number of characters wide, and an array, and it generates a listing to fit)


In reply to Re: Printing an array columnwise or rowwise by jhourcle
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.