Have you ever wondered how programs like ls generate columns of sorted output that you read down the columns instead of across the rows? For example:
awk cp ed login mount rmdir sum basename csh egrep ls mt sed sync cat date fgrep mail mv sh tar chgrp dd grep mkdir ps sort touch chmod df kill mknod pwd stty vi chown echo ln more rm su
Example 4.2 does this.
#!/usr/bin/perl -w # words - gather lines, present in columns use strict; my ($item, $cols, $rows, $maxlen); my ($xpixel, $ypixel, $mask, @data);
The most obvious way to print out a sorted list in columns is to print each element of the list, one at a time, padded out to a particular width. When you're about to hit the end of the line, generate a newline. But that only works if you're planning on reading each row left to right. If you instead expect to read it down each column, this approach won't do.
The words program is a filter that generates output going down the columns. It reads all input, keeping track of the length of the longest line seen. Once everything has been read in, it divides the screen width by the length of the longest input record seen, yielding the expected number of columns.
Then the program goes into a loop that executes once per input record, but the output order isn't in the obvious order. Imagine you had a list of nine items:
Wrong Right ----- ----- 1 2 3 1 4 7 4 5 6 2 5 8 7 8 9 3 6 9
program does the necessary calculations to print out elements
To figure out the current window size, this program does an