This will loop a few times until it finds the best combination of lines/columns:

use strict; my @a = sort qw( B Digest Filter MIME SDBM_File Time util ByteLoader DynaLoader GDBM_File NDBM_File Safe Unicode Cwd Encode I18N ODBM_File Socket XS DB_File Errno IO Opcode Storable attrs Data Fcntl IPC POSIX Sys re Devel File List PerlIO Thread threads ); sub try { my ( $n, @a ) = @_; my $lines = int ( 1 + ( @a + $n - 1 ) / $n ); my @result; my $width = 0; for ( 1 .. $n ) { my @b = splice( @a, 0, $lines - 1 ); my $colwidth = (sort( { $a <=> $b } map { 1+length $_ } @b ))[-1]; push @result, [ $colwidth, @b ]; $width += $colwidth; } return $width, @result; } my $SCREEN_WIDTH = 80; my $col = 1; my $last_width = 0; my @result; my $width; my @last_result; while(1) { ( $width, @result ) = try( $col, @a ); last if $width > $SCREEN_WIDTH || $#{$result[0]} <= 1; $col++; $last_width = $width; @last_result = @result; }; @result = @last_result if defined @last_result; my @lines; for my $col ( @result ) { my $width = shift @$col; $_ = sprintf( "%-${width}s", $_ ) for ( @$col ); } for my $line ( 0 .. $#{$result[0]} ) { print $result[$_][$line] for 0 .. $#result; print "\n"; }

Output (using $SCREEN_WIDTH=50 so that if fits here):

B Encode IPC SDBM_File XS ByteLoader Errno List Safe attrs Cwd Fcntl MIME Socket re DB_File File NDBM_File Storable threads Data Filter ODBM_File Sys util Devel GDBM_File Opcode Thread Digest I18N POSIX Time DynaLoader IO PerlIO Unicode

update: changed one of the loop-end controls.


In reply to Re: 'ls -C' column style by fglock
in thread 'ls -C' column style by hv

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.