home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!airgun!starr@wg2.waii.com
- From: rfs@se28.wg2.waii.com (Robert Starr)
- Newsgroups: comp.lang.perl
- Subject: an ls -C Perl function
- Keywords: perl
- Message-ID: <1992Nov13.141515@se28.wg2.waii.com>
- Date: 13 Nov 92 20:15:15 GMT
- Sender: news@airgun.wg.waii.com
- Reply-To: starr@wg2.waii.com
- Organization: Western Geophysical
- Lines: 81
- Nntp-Posting-Host: se28.wg2.waii.com
-
- Here is a function to take a list of file names, and sort it as an
- ls -C does (sorted down columns). I find myself spewing out file names
- often, and missed having them not be ordered as ls -C does. If there
- was a Unix filter to do this, I couldn't find it. But it's nice to
- have a Perl ditty to do the same thing anyway.
-
- Note the completely non-portable setting of TIOCGWINSZ to get the
- window size. The problem seems to be that proper .ph files cannot be
- created on the Sparc, since the computation of TIOCGWINSZ involves
- using the size of a data structure. Any suggestions?
-
- #--------%<----------------
- #!/bin/perl
- # $Id: lsC.pl,v 1.3 1992/11/13 19:59:25 rfs Exp $
- #
- # $Log: lsC.pl,v $
- #Revision 1.3 1992/11/13 19:59:25 rfs
- #Minor cleanup.
- #
- #Revision 1.2 1992/11/11 23:17:34 rfs
- #Added int() to $nrows computation.
- #
- #Revision 1.1 1992/11/11 23:02:05 rfs
- #Initial revision
- #
-
- # Usage: @out = &LsC(@filenames);
- # Returns an array of filenames, sorted as ls -C would do. The returned
- # array of lines aren't newline terminated.
- #
- # NOTE: very non-portable setting of $TIOCGWINSZ. This was for Sparc.
- #
- # Author: RF Starr (starr@wg2.waii.com)
-
- sub LsC {
- package LsC;
- local(@f) = @_;
- local($maxlen, $_);
- local(@out) = ();
-
- $nc = &main'_GetNumColumns() unless (defined($nc));
- @files = sort(@f);
- # find widest file name
- $maxlen = 0;
- $cnt = 0;
- foreach (@files) {
- $len = length($_);
- $maxlen = $len if ($len > $maxlen);
- $cnt++;
- }
- $nperline = $nc/($maxlen+1);
- $nperline = int($nperline);
- $nrows = int($cnt/$nperline);
- $nrows++ if ($cnt % $nperline);
- $fmt = "%-$maxlen.$maxlen" . "s ";
- for ($i=0; $i < $nrows; $i++) {
- $out[$i] = '';
- }
- $j = 0;
- for ($i=0; $i < $cnt; $i++) {
- $out[$j] .= sprintf($fmt, $files[$i]);
- $j++;
- $j = 0 if ($j >= $nrows);
- }
- return @out;
- }
-
- sub _GetNumColumns {
- package _GetNumColumns;
-
- $nc = 80;
- # You may need to change this constant
- $TIOCGWINSZ = 0x40087468;
- $wt = "S S S S";
- $ws = pack($wt, 0, 0, 0, 0);
- ioctl(STDIN, $TIOCGWINSZ, $ws);
- ($nrow, $ncol) = unpack($wt, $ws);
- $nc = $ncol if ($ncol);
- return $nc;
- }
- 1;
-