fireartist has asked for the wisdom of the Perl Monks concerning the following question:
I think the way I've done it must be quite inefficient, as it itterates through the entire array 3 times - firstly to get the max single length of the array entries - secondly to pad out shorter entries with space, up to the max length, thirdly to print it all out.one two three four five six seven eight nine ten
My array will always be pre-sorted alphabetically.use strict; my @array = qw/one two three four five six seven eight nine ten/; my $cols = 3; my $max = 0; foreach (@array) { if (length >= $max) { $max = length $_; } } foreach (@array) { my $length = length $_; if ($length < $max) { $_ .= (' ' x ($max - $length)); } } while (@array) { unless (scalar @array >= $cols) { $cols = scalar @array; } print join(' ', splice(@array, 0, $cols) ), $/; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: Printing an array in columns - improvements?
by merlyn (Sage) on Jul 18, 2002 at 15:12 UTC | |
by fireartist (Chaplain) on Jul 18, 2002 at 15:39 UTC | |
|
Re: Printing an array in columns - improvements?
by Abigail-II (Bishop) on Jul 18, 2002 at 15:48 UTC | |
by BrowserUk (Patriarch) on Jul 18, 2002 at 16:57 UTC | |
by demerphq (Chancellor) on Jul 18, 2002 at 18:20 UTC | |
|
Re: Printing an array in columns - improvements?
by Fletch (Bishop) on Jul 18, 2002 at 15:13 UTC | |
|
(dooberwah) Re: Printing an array in columns - improvements?
by dooberwah (Pilgrim) on Jul 18, 2002 at 15:32 UTC |