[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Interleaving arrays



1999-11-10-13:30:18 tomr@aceldama.com:
> 
>    @cats = @cats[map (($_/2 + ($_ % 2) * $#cats/2), 0..$#cats)];
> 
> [...] Anyone else have comments?

You are a sick little monkey. I like that. :-)

Seriously, this is something I frequently need to do, and I've never seen such
a lovely way of saying it. Next natural question would be, does it keep
working for ncols!=2. Looks to me like it does. So my typical application
would look more like

    #!/usr/bin/perl -w
    use strict;
    use Getopt::Std;
    use vars qw($opt_w $opt_g);
    $opt_w = 78;
    $opt_g =  2;
    getopts('g:w:') or die "syntax: $0 [-g gutter] [-w width] [file ...]\n";

    my @data = <>; chomp @data;
    my $maxwidth = 0;
    for (@data) { $maxwidth = length if length > $maxwidth; }
    for (@data) { $_ .= ' ' x ($maxwidth - length); }
    $maxwidth += $opt_g; # gutter between columns
    my $ncols = int($opt_w / $maxwidth);
    my $nrows = $#data / $ncols;
    @data = @data[ map { $_/$ncols + ($_ % $ncols) * $nrows } 0..$#data ];
    while (@data) {
    	print join((' ' x $opt_g), splice(@data, 0, $ncols)), "\n";
    }

Well, that's creapy, it works. I'm still not perfectly sure why nrows doesn't
need to be rounded up.

Anybody know an elegant way to do multicolumn output the way ls(1) does, with
the column padding dependant only on the widths of the elements that end up in
those columns?

-Bennett

PGP signature