in reply to 'ls -C' column style
This one loops over the list of items once (at most). It computes the widths for all possible numbers of columns as it goes, eliminating cases of too-many columns when it determines that they would be too wide.
Fully tested and now it does not waste time on column counts over about @items/2 and (update 3) chooses single-row output correctly.
#!/usr/bin/perl -w use strict; my( $maxWid )= ( @ARGV, 79 ); my @items = qw( B ByteLoader Cwd DB_File Data Devel Digest DynaLoader Encode Errno Fcntl File Filter GDBM_File I18N IO IPC List MIME NDBM_File ODBM_File Opcode POSIX PerlIO SDBM_File Safe Socket Storable Sys Thread Time Unicode XS attrs re threads util ); print '='x$maxWid, $/; print Columns( $maxWid, \@items ); exit( 0 ); sub Columns { my( $maxWid, $avItems )= @_; my $maxCols= 1 + $#$avItems/2; my @height= ( 0, map 1+int($#$avItems/$_), 1..$maxCols ); my @total= ( $#$avItems, 0 .. ($maxCols-1) ); my @width; for my $i ( 0..$#$avItems ) { my $len = length( $avItems->[$i] ); $total[0] += $len; for my $cols ( 1 .. $maxCols ) { for( $width[ $cols ][ $i/$height[$cols] ] ) { $_ ||= 0; if( $_ <= $len ) { $total[$cols] += $len - $_; if( $maxWid < $total[$cols] ) { $maxCols= $cols - 1; } $_= $len; } } last if $maxCols < $cols; } last if $maxCols < 2; } $maxCols ||= 1; my $height= $height[$maxCols]; @width= @{ $width[$maxCols] }; if( $total[0] <= $maxWid ) { $maxCols= @$avItems; $height= 1; @width= (0) x $maxCols; } my $text= ''; for my $l ( 1 .. $height ) { my $i= $l - 1; my $c= 0; while( $i < @$avItems ) { my $item= $avItems->[$i]; $i += $height; if( $i < @$avItems ) { $text .= sprintf "%-$width[$c++]s ", $item; } else { $text .= $item . $/; } } } return $text; }
- tye
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: 'ls -C' column style (sideways)
by BrowserUk (Patriarch) on Nov 04, 2004 at 23:08 UTC | |
by tye (Sage) on Nov 05, 2004 at 01:10 UTC | |
by BrowserUk (Patriarch) on Nov 05, 2004 at 02:33 UTC | |
by hv (Prior) on Nov 05, 2004 at 11:45 UTC | |
|
Re^2: 'ls -C' column style (sideways)
by hv (Prior) on Nov 05, 2004 at 11:07 UTC |