After much unsucessful searching for a function/method to print a list in a format similar to the output of the unix 'dir' command, I've written this small script.
It turns,
@array = qw/one two three four five six seven eight nine ten/
Into,
one two three
four five six
seven eight nine
ten
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.
Can anyone offer me improvements, or suggest alternative ways of approaching this?
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) ), $/;
}
My array will always be pre-sorted alphabetically.
This script doesn't print the list alphabetically down-ways, but I don't really need that anyway.
The array will actually be populated from searches on the 'linux.words' file, so it may contain many indices.
Thanks,
Carl
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.