in reply to 'ls -C' column style
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: 'ls -C' column style
by hv (Prior) on Nov 05, 2004 at 10:13 UTC |