Debian Codegraph @

showtable

raw
1 #!/usr/bin/env perl
2 # showtable - read data and show it
3 #
4 # Copyright (C) 1996-2013 Alan K. Stebbens <[email protected]>
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 #
20 #
21 # showtable [options] [file]
22 #
23 # This script acts as a filter, reading data in columns and displaying
24 # the data in a nicely formatted output. The output can be either
25 # a list style, simple table, boxed table, or HTML-formatted table.
26 #
27 # The input styles accepted are: tab-delimited, comma-delimited,
28 # list-style, simple-style tables, and boxed tables.
29 #
30 # The default is tab-delimited data
31 #
32 # Use -d<char> to set the field separation character. Eg: -d,
33 #
34 # Other options: -table, -html, -box, -list
35 #
36 # If no file is given, STDIN is used by default.
37 #
38 # $Id$
39 # $Source$
40 #
41 # Author: Alan K. Stebbens <[email protected]>
42 #
43
44 ($DIR,$PROG) = $0 =~ m=^(.*/)?([^/]+)$=;
45 chop($DIR = `pwd`) unless defined($DIR);
46 $DIR =~ s=/$==;
47
48 $VERSION = '4.5';
49
50 unshift(@INC,'.');
51 unshift(@INC,'blib/lib') if -d 'blib/lib'; # for testing
52
53 use Data::ShowTable;
54
55 sub ShowData;
56 sub ReadTableInput;
57 sub ReadListInput;
58 sub NextRow;
59 sub max;
60
61 sub err {
62 my $fmt = shift;
63 $fmt .= "\n" unless $fmt =~ /\n$/;
64 printf STDERR $fmt,@_;
65 }
66
67 sub usage {
68 err @_ if $#_ >= 0;
69 err <<EOF;
70 usage: $PROG [options] [file]
71 Read the file, or STDIN by default, and produce a nicely formatted listing
72 of columnar data. By default, columns of data should be separated by tabs,
73 and is assumed to have no titles. Lines of all spaces and any of the
74 characters "-+_=" will be ignored as separator lines, unless -nodashes is
75 given.
76
77 Options affecting input:
78 -br(eak)=STR set the inter-column break character to "STR". The default
79 is "\t" (a tab).
80 -dSTR set the delimiter string (same as "-break=STR").
81 -nod(ashes) Do not look for lines of separators, such as dashes, equal
82 signs, or underlines (if they occur, they will be part of
83 the "data".
84 -t(itles)[=NN] Treat the first NN rows of data as column titles; multiple
85 words in the column titles may wrap vertically. If NN is
86 omitted, it defaults to 1. If no -titles is given at all,
87 NN defaults to 0.
88 -st(rip) Strip blanks from around the column values (implied with
89 $InputType eq 'box').
90 -nos(trip) Don't strip blanks around the column values.
91 -i(nput)=TYPE Set the input type; currently TYPE can be "list", "box",
92 "table", or "simple". Default is "box".
93
94 The options controlling the output are:
95 -s(imple) use a simple table format (without wrapped columns)
96 -t(able) use a table format (handles wrapped column values)
97 -l(ist) use a list style format
98 -b(ox) use a "boxed" style table
99 -ht(ml) use HTML-formating
100 -noh(eaders) do not output any headers on the tables; -titles=0 implies
101 this option.
102 -ti(tles)=name1,name2,...,nameN
103 Define the output column titles explicitly; "name1" cannot
104 begin with a number. Implies "-titles=0".
105 -w(idth)=NN Define the maximum width of the table; if this not given,
106 the maximum is the sum of all given column widths.
107 -cw(idths)=w1,w2,...,wN
108 Define individual column widths; the last width applies to
109 any remaining columns. Each column may be given as an
110 integer, representing a character count, or a fraction
111 or percentage, representing percentages.
112 -fN1,N2... select fields to display by index; N-M is a range of fields.
113 -fields=Name1, Name2, ...
114 select fields to display by names.
115 -h(elp) Display this string.
116
117 HTML-only options (their usage implies -html):
118 -noe(scape) Do not perform HTML escape sequences; this will allow
119 data with embedded HTML to be displayed properly. Implies
120 the -html option.
121 -attr(ibutes)='attr1 attr2 ...'
122 Define the table attributes, which get inserted into the
123 <TABLE> token.
124 -t(itle)f(ormats)=fmt1;fmt2;...;fmtN
125 Define the HTML formats for the titles.
126 Implies -html.
127 -d(ata)f(ormats)=fmt1;fmt2;...;fmtN
128 Define the HTML formats for the data values in each column.
129 Implies -html.
130 -url(s)=col1=url1,col2=url2,...
131 Define the URL mappings for given column names. Multiple
132 -url options may be given.
133 EOF
134 exit;
135 }
136
137 $break_str = "\t"; # tab for default break str
138 $Titles = 0; # assume no input titles
139 $#Titles = -1; # assume no output titles
140 @Fields = (); # no explicit field selections
141 %URLs = (); # no URLs initially
142
143 $InputType = '';
144 $Strip_Spaces = '';
145 $NoStrip_Spaces = '';
146 $Show_Mode = 'Box'; # by default
147 $Width = 0; # no width limit by default
148
149 $nofile = 1;
150
151 while ($_ = shift(@ARGV)) {
152 if (/^-d(\W+)?$/) { # -dSTR
153 $break_str = $1 || shift || usage "$PROG: Missing argument to -d\n";
154 next;
155 }
156 if (/^-f(\d.*)/) { # -fN1,N2,...
157 $value = $1;
158 # convert possible range spec
159 $value =~ s/\b(\d+)-(\d+)\b/join(',',$1..$2)/e;
160 @Fields = split(/[:, ]/,$value);
161 next;
162 }
163 usage if !index('-help',$_);
164 if (!index('-strip',$_)) { # -strip
165 $Strip_Spaces = 1;
166 $NoStrip_Spaces = '';
167 } elsif (!index('-nostrip',$_)) { # -nostrip
168 $NoStrip_Spaces = 1;
169 $Strip_Spaces = '';
170 } elsif (!index('-table',$_) || !index('-simple',$_)) { # -table, -simple
171 $Show_Mode = 'Table';
172 } elsif (!index('-list', $_)) { # -list
173 $Show_Mode = 'List';
174 } elsif (!index('-box',$_)) { # -box
175 $Show_Mode = 'Box';
176 $Strip_Spaces = 1 unless $NoStrip_Spaces;
177 } elsif (!index('-html',$_)) { # -html
178 $Show_Mode = 'HTML';
179 } elsif (!index('-noescape',$_)) { # -noescape
180 $No_Escape = 1;
181 $Show_Mode = 'HTML';
182 } elsif (!index('-noheaders',$_)) { # -noheaders
183 $No_Header = 1;
184 } elsif (!index('-nodashes',$_)) { # -nodashes
185 $No_Dashes = 1;
186 } elsif (/^(-\w+)(?:[:=](.*))?/) { # -OPTION=VALUE
187 ($_, $value) = ($1, $2);
188 if (!index('-titles',$_)) { # -titles=NN, -titles=NAME,..
189 if ($value =~ /^\d/ || $value eq '') { # -titles=NN?
190 $Titles = $value ne '' ? $value : 1;
191 } else { # -titles=name,name2,...,nameN
192 @Titles = split(/[:, ]/,$value);
193 $Titles = 0; # no titles in the datastream
194 }
195 } elsif (!index('-input',$_)) { # -input=TYPE?
196 $value = lc($value);
197 if (!index('box',$value)) { # -input=box?
198 $InputType = 'box';
199 $Titles = 1 unless $Titles >= 1;
200 } elsif (!index('list',$value)) {# -input=list?
201 $InputType = 'list';
202 } elsif (!index('table', $value)) { # -input=table?
203 $InputType = 'table';
204 $Titles = 1 unless $Titles >= 1;
205 } elsif (!index('simple', $value)) {# -input=simple?
206 $InputType = 'simple';
207 } else {
208 usage "$PROG: bad -input TYPE";
209 }
210 } elsif (!index('-fields',$_)) { # -fields=Name1, Name2, ...
211 # convert range spec
212 $value =~ s/\b(\d+)-(\d+)\b/join(' ',$1..$2)/e;
213 @Fields = split(/[:, ]+/,$value);
214 } elsif (!index('-break',$_)) { # -break=STR
215 $break_str = $value ne '' ? $value : "\t";
216 if ($break_str =~ /\\/) { # any escape sequences?
217 $break_str =~ s/"/\\"/g; # yes, escape any quotes
218 $break_str = eval('"'.$break_str.'"'); # evaluate a string
219 }
220 } elsif (!index('-width',$_)) { # -width=NUM
221 $value =~ /^\d+$/ or usage "$PROG: width must be a number.";
222 $Width = 0 + $value;
223 } elsif (!index('-cwidths',$_)) { # -cwidths=N1,N2,...,NM
224 @Cwidths = split(/[,: ]/,$value);
225 if (grep(!/^(\.?\d+|\d+%)?$/,@Cwidths)) {
226 usage "$PROG: bad format for -cwidths.";
227 }
228 } elsif (!index('-titleformats',$_) || !index('-tformats',$_)) {
229 my @tformats = split(/[;|]/,$value); # get the title formats
230 foreach (@tformats) {
231 next if /^<?($HTML_Elements)/i; # HTML element ok?
232 usage "$PROG: bad HTML format element: '%s'", $1;
233 }
234 push(@Tformats,@tformats); # allow multiple options
235 $Show_Mode = 'HTML';
236 } elsif (!index('-dataformats',$_) || !index('-dformats',$_)) {
237 my @dformats = split(/[;|]/,$value); # get the title formats
238 foreach (@dformats) {
239 next if /^<?(?:$HTML_Elements)/i; # HTML element ok?
240 usage "$PROG: bad HTML format element '%s'", $_;
241 }
242 push(@Dformats,@dformats); # allow multiple options
243 $Show_Mode = 'HTML';
244 } elsif (!index('-urls',$_)) {
245 # parse COL1=URL1,COL2=URL2,...
246 # or: COL1:URL1,COL2:URL2,...
247 my @urldefs = split(/[,|]/, $value); # get the different URLs
248 my $urldef;
249 foreach $urldef (@urldefs) {
250 my ($col, $url) = split(/[=:]/,$urldef,2);
251 if ($col ne '' && $url ne '') { # both defined?
252 $URLs{$col} = $url; # save the mapping
253 } elsif ($col ne '' || $url ne '') {
254 usage "$PROG: bad URL format element: '%s'", $urldef;
255 }
256 }
257 $Show_Mode = 'HTML'; # make sure
258 } elsif (!index('-attributes',$_)) {
259 $table_attributes .= ' '.$value; # build up the list
260 $Show_Mode = 'HTML';
261 } else {
262 usage "$PROG: Unknown option: $_";
263 }
264 } elsif (/^-/) {
265 usage "$PROG: Unknown option: $_";
266 } elsif (-f) { # does the file exist?
267 open(STDIN,"<$_") ||
268 die "$PROG: Can't open $_ for input: $!\n";
269 ShowData;
270 close(STDIN);
271 $nofile = 0;
272 } else {
273 err "File $_ does not exist.";
274 exit 1;
275 }
276 }
277
278 ShowData if $nofile;
279
280 exit;
281
282
283 # $type = guess_type $value
284
285 sub guess_type {
286 local $_ = shift;
287 &PlainText if $Show_Mode eq 'HTML'; # remove HTML effects if -html
288 # so they aren't part of the typing
289 s/^\s+//; s/\s+$//; # trim leading & trailing blanks
290 /^$/ && return 'null'; # null type
291 /^([01tf]|yes|no|on|off)$/i && return 'bool'; # 0, 1, yes, no, on, off, t, f
292 m=^\d{2,4}[-/.]\d{1,2}[-/.]\d{1,2}$= && return 'date'; # mm/dd/yy, yy/mm/dd, yyyy.mm.dd, yyyy-mm-dd
293 m=^\d{1,2}[-/.]\d{1,2}[-/.]\d{2,4}$= && return 'date'; # dd.mm.yyyy, d.m.yy, dd-mm-yy
294 /^\w{3,9} \d{1,2}, \d{4}/ && return 'date'; # mmmm dd, yyyy
295 /^\d{1,2}[- ]\w{3}[- ]\d{2,4}$/ && return 'date'; # dd mmm yyyy
296 /^\d\d:\d\d(:\d\d)?$/ && return 'time'; # hh:mm:ss
297 /^[-+]?\d+$/ && return 'int'; # +-nnnn
298 /^[-+]?[\d.]+(E[+-]?\d+)?$/ && return 'real'; # +-nnn.nnn(E+-nn)
299 /^[-+]?[\d.]\%$/ && return 'pct'; # nn%, nn.n%, -nn.nnn%
300 /^-?\(?\$[ \d,.]+\)?(?: *CR)?$/ && return 'money'; # $ nn,nnn.nn or ($ nnn,nnn.nn)
301 /^-?\(?[\d]+,[\d,]+(\.(\d\d)?)?\)?$/&& return 'money'; # nnn,nnn.nn or ( nnn,nnn.nn)
302 /^['"]|["']$/ && return 'string'; # "xxxx"
303 /^\w+$/ && return 'symbol';
304 /\n/ && return 'text';
305 return 'char';
306 }
307
308 # Do type conversion
309
310 sub new_type {
311 my @types = @_;
312 my $type1 = $types[0];
313 my $type2 = $types[1];
314
315 # trivial conversions
316 $type1 eq '' && return $type2;
317 $type2 eq '' && return $type1;
318 $type1 eq $type2 && return $type1;
319
320 # handle null types
321 $type1 eq 'null' && return $type2;
322 $type2 eq 'null' && return $type1;
323
324 # These types supercede others
325 grep(/text/i, @types) && return 'text';
326 grep(/string/i, @types) && return 'string';
327 grep(/char/i, @types) && return 'char';
328
329 # Now do finer-grain conversions
330 grep(/money/i, @types) && return 'money';
331 grep(/pct/i, @types) && return 'pct';
332 grep(/real/i, @types) && return 'real';
333 grep(/int/i, @types) && return 'int';
334 grep(/symbol/i, @types) && return 'symbol';
335 grep(/bool/i, @types) && return 'bool';
336
337 $type1; # huh?
338 }
339
340 sub ShowData {
341 @Data = ();
342 # reset titles if they are coming from the data stream
343 #@Titles = () if $Titles > 0;
344 @Types = ();
345 @Widths = ();
346 my ($titles, $data, $maxcols);
347 if ($InputType eq 'list') {
348 ($titles, $data, $maxcols) = ReadListInput;
349 } else {
350 ($titles, $data, $maxcols) = ReadTableInput;
351 }
352 my @titles = @$titles;
353 @Data = @$data;
354
355 # Make the fields selection
356 if (@Fields) {
357 # build a field index list
358 my ($f,$fx);
359 my %fields = ();
360 my @fields = (); # an index list
361 @fields{@titles} = (0..$#titles); # generate indexes
362 foreach $f (@Fields) {
363 if ($f =~ /^\d+$/) { # a numeric index?
364 $f--; # convert to origin zero
365 push(@fields,$f) if $f <= $maxcols && $f >= 0;
366 next;
367 }
368 # Lookup a field name and use its index
369 if (($fx = $fields{$f}) ne '') {
370 push(@fields,$fx);
371 }
372 }
373 # now, given the field index array, splice each row array according
374 # to the field indexes
375 my $r;
376 for ($r = 0; $r <= $#Data; $r++) { # foreach row of data..
377 $row = $Data[$r]; # get the row
378 @$row = @$row[@fields]; # slice out the desired fields
379 }
380 $maxcols = $#fields; # set the other vars
381 @titles = @titles[@fields]; # slice out the titles
382 }
383
384 # Now, map external titles onto the titles array, allowing
385 # user-given titles to override the built-in titles (if any).
386 if ($No_Header) { # if no headers, no titles
387 @titles = ();
388 } elsif ($#Titles >= 0) { # map @Titles onto @titles
389 my ($c,$t);
390 for ($c = 0; $c <= $maxcols; $c++) {
391 if (($t = $Titles[$c]) ne '') { # user-given title
392 $titles[$c] = $t; # overrides built-in title
393 } elsif ($titles[$c] eq '') { # otherwise, use default title
394 $titles[$c] = sprintf("Field_%d", $c + 1);
395 }
396 }
397 }
398
399 # Scan the column widths, where none are given, and if a total width
400 # was given, calculate a fraction.
401 my $cols_left = length($Width) ? $Width : # maximum columns left
402 $Show_Mode ne 'HTML' ? $ENV{'COLUMNS'} : 0;
403
404 if ($cols_left > 0) { # cols == 0 means no limit
405 # We must reduce the available columns by the formatting requirements
406 # of the display format
407 $cols_left -= $maxcols * 3 + 2 if $Show_Mode eq 'Box';
408 $cols_left -= $maxcols * 2 - 1 if $Show_Mode eq 'Table';
409
410 my ($c, $w, $cols);
411 for ($c = 0; $c <= $maxcols; $c++) { # for each column..
412 $w = $c <= $#Cwidths ? $Cwidths[$c] : $Cwidths[$#Cwidths];
413 if ($w ne '') { # is there a value?
414 # If the width is a fraction or percentage...
415 if ($w =~ /[.%]/ || ($w > 0 && $w < 1.0)) {
416 $w = $1 / 100.0 if $w =~ /^(\d+)%/; # convert NN% to fraction
417 $w = int($cols_left * $w); # convert fraction to width
418 }
419 $w = 1 unless $w > 0; # guarantee 1 col min
420 $cols_left -= $w; # keep an accounting
421 $cols_left = 0 if $cols_left < 0;# keep sane
422 $Widths[$c] = $w; # set the column width
423 }
424 }
425 }
426
427 my ($c, $r, $val, $row, $type, $newtype); # some vars
428 # Now let's analyze the data
429 for ($c = 0; $c <= $maxcols; $c++) { # Scan each column
430 $type = ''; # assume no default
431 for ($r = 0; $r <= $#Data; $r++) { # scan each row
432 $row = $Data[$r]; # get the row data
433 if (defined($row->[$c])) {
434 $val = $row->[$c]; # get the column data
435 } else {
436 $row->[$c] = '';
437 }
438 $newtype = guess_type $val;
439 $type = new_type $type, $newtype;
440 }
441 $Types[$c] = $type;
442 }
443
444 local $theRow;
445 my $theRowSub = sub { &ShowRow( $_[0], \$theRow, \@Data ); };
446 ShowTable
447 { show_mode => $Show_Mode,
448 max_width => $Width > 0 ? $Width : '',
449 titles => \@titles,
450 types => \@Types,
451 widths => \@Widths,
452 row_sub => $theRowSub,
453 no_escape => $No_Escape,
454 table_attrs => $table_attributes,
455 tformats => \@Tformats,
456 dformats => \@Dformats,
457 url_keys => \%URLs,
458 };
459 }
460
461 # ($titles, $data, $maxcols) = ReadTableInput
462 #
463 # $titles is a ref to an array of titles
464 # $data is a ref to an array of rows (arrays of values)
465 # $maxcols is the maximum columns index in any of the rows.
466
467 # The global $Titles determines how many titles rows there are.
468 # Unless $NoDashes is set, this can be determined imperically
469 # if there are titles and a separator row, or explicitly with
470 # -titles=NN.
471
472 sub ReadTableInput {
473 my @data;
474 my @titles;
475 my $data;
476 if ($Titles > 0) {
477 @titles = @{&NextRow};
478 # if there are multiple lines of titles, combine them
479 my ($limit, $r, $c);
480 for ($r = 1; $r < $Titles; $r++) {
481 $data = NextRow; # get the next row of data
482 $limit = max $#titles, $#$data;
483 for ($c = 0; $c <= $limit; $c++) {
484 $titles[$c] .= ' '.$data->[$c]; # combine titles
485 }
486 }
487 foreach (@titles) { # clean up the names
488 s/^\s+//; # trim leading &
489 s/\s+$//; # trailing blanks
490 s/\s+/ /g; # & squeeze middle blanks
491 }
492 } else {
493 $#titles = -1; # no titles at all
494 }
495 my $maxcols = 0;
496 while ($data = NextRow) {
497 push(@data, $data); # collect the data
498 $maxcols = $#$data if $#$data > $maxcols;
499 }
500 (\@titles, \@data, $maxcols);
501 }
502
503 # Read in next row of data into $_; return \@data.
504 #
505 # If $InputType is 'box', input with "| foo | bar | ... |" is
506 # boxed input, and the bars are removed. Also, if "|<" or ">|"
507 # occur, then the next row of data is appended to the current
508 # row.
509 #
510 # Unboxed input is split by tabs (or the $break_str)
511
512 sub NextRow {
513 my @row;
514 my ($continue, $append);
515 while (1) {
516 $_ = <STDIN>;
517 last unless $_;
518 chomp;
519 unless ($InputType) {
520 $InputType = 'box' if /^\s*([\+:|*])[-+=:*|_]*$1\s*$/;
521 }
522 next if !$No_Dashes && /^[-_=+ \t]*$/;
523
524 my @data;
525 # If boxed input, remove boxing characters and split with the
526 # box bar character
527 if (/^\s*([|:]).*$1\s*$/ && $InputType eq 'box') {
528 # The data is boxed--remove boxing data
529 my $bar = $1;
530 my $continue = />\Q$bar\E/; # is there a continuation?
531 my $append |= /\Q$bar\E</; # should this be appended?
532 s/^\s*\Q$bar\E<?\s*//; # remove leading bar (if any)
533 s/\s*>?\Q$bar\E\s*$//; # remove trailing bar (if any)
534 if ($NoStrip_Spaces) { # nostrip?
535 @data = split(/>?\Q$bar\E<?/);
536 } else {
537 @data = split(/\s*>?\Q$bar\E<?\s*/);
538 }
539 } else { # not in box mode
540 if ($break_str eq " \t" or $break_str eq "\t ") {
541 @data = split(' ');
542 } elsif ($Strip_Spaces) {
543 @data = split(/\s*\Q$break_str\E\s*/);
544 } else {
545 @data = split(/\Q$break_str\E/);
546 }
547 if ($InputType eq 'table') { # check for table wraps
548 $append |= grep(s/^<//,@data); # see if any appends
549 $continue = grep(s/>$//,@data); # see if any continuations
550 }
551 }
552 if ($append) {
553 my $maxcol = max($#data, $#row);
554 for ($i = 0; $i < $maxcol; $i++) {
555 $row[$i] .= $data[$i];
556 }
557 $append = ''; # append done (for now)
558 } else {
559 @row = @data; # initialize the row data
560 }
561 # quit the loop unless we have a continuation of data
562 last unless $continue;
563 $append = $continue;
564 $continue = '';
565 }
566 $#row >= 0 ? \@row : undef;
567 }
568
569 # ( $titles, $data, $maxcol) = ReadListInput;
570 #
571 # $titles is a ref to an array of titles.
572 # $data is a ref to an array of rows (arrays of columns) of data.
573 # $maxcol is the maximum number of columns in any one row of the data.
574
575 # The order of the columns in the resulting array of rows is defined
576 # by the names in the @Titles array, or the order of occurance of the
577 # columns in the lists of column names.
578
579 sub ReadListInput {
580 my @data;
581 my @titles;
582 my ($key, $lastkey, $val);
583 local $_ = 'go';
584 my $maxcol = 0;
585 my $titlesref;
586 while (length) {
587 my %row;
588 # Read another "row" of list data
589 while (1) {
590 defined($_ = <STDIN>) or last;
591 last if /^\s*$/; # stop on the row boundary
592 chomp;
593 ($key, $val) = /^\s*([\w_.:\/-]+)?\s*:[ \t]?(.*)/;
594 if ($key ne '') {
595 $row{$lastkey = $key} = $val;
596 push(@titles,$key) unless grep(/^\Q$key\E/,@titles);
597 } else {
598 $val = ' '.$val
599 unless $val =~ /^ / || $row{$lastkey} =~ / $/;
600 $row{$lastkey} .= $val;
601 }
602 }
603 my @row;
604 $titlesref = $#Titles >= 0 ? \@Titles : \@titles;
605 foreach $column (@$titlesref) {
606 if (exists $row{$column}) {
607 push(@row,$row{$column});
608 } else {
609 push(@row,undef); # same as SQL NULL
610 }
611 }
612 push(@data,\@row); # save the row
613 $maxcol = $#row if $#row > $maxcol;
614 }
615 $maxcol = $#titles if $#titles > $maxcol;
616 $titlesref = $#Titles >= 0 ? \@Titles : \@titles;
617 ($titlesref, \@data, $maxcol);
618 }
619
620 # $max = max @values;
621 # Return the maximum of a list of values
622
623 sub max {
624 my $max = shift;
625 foreach (@_) { $max = $_ if $_ > $max; }
626 $max;
627 }
628
629 __END__
630
631 =head1 NAME
632
633 B<showtable> - Show data in nicely formatted columns
634
635 =head1 USAGE
636
637 B<showtable> [-I<options>] [I<file>]
638
639 =head1 DESCRIPTION
640
641 B<Showtable> reads an input data stream and displays it in a nicely
642 formatted listing, with exact formatting depending upon the options.
643 The input stream, I<file> or C<STDIN> by default should consist of data
644 separated by tabs or the defined I<separator> character (see B<-d>).
645
646 The actual output formatting is peformed by the B<ShowTable> module.
647
648 =head1 OPTIONS
649
650 There are two general sets of options: those which help determine the format of the
651 input, and those which determine the format of the output.
652
653 =head2 B<Options affecting input>
654
655 =over 10
656
657 =item B<-break=>I<str>
658
659 Set the inter-column break string to "I<str>". The default
660 is a tab ("C<\t>"). If B<-strip> is also given, blanks surrounding
661 the break string will also be ignored.
662
663 =item B<-d>I<str>
664
665 This is the same as C<-break=>I<str>.
666
667 =item B<-nod(ashes)>
668
669 Do not ignore lines of separators, such as dashes, equal
670 signs, or underlines. If B<-nodashes> is given, and these lines do occur
671 in the stream, they will be treated as normal data.
672
673 =item B<-ti(tles)[=>I<NN>B<]>
674
675 Treat the first I<NN> rows of data as column titles; multiple
676 words in the column titles may wrap vertically. If I<NN> is
677 omitted, it defaults to 1. No B<-titles> option is the same
678 as B<-titles=0>.
679
680 =item B<-in(put)=>I<type>
681
682 Set the input type as I<type>, which can be one of: I<box>, I<list>, I<table>,
683 or I<simple>. A I<simple>-type table is the same as a I<table>-type,
684 but no wrapping characters are recognized.
685
686 =item B<-s(trip)>
687
688 Strip blanks from around the column values.
689
690 =item B<-nos(trip)>
691
692 Do not strip blanks from the input. Useful if there is formatted or aligned
693 data within a boxed table.
694
695 =back
696
697 =head2 B<Options affecting output>
698
699 =over 10
700
701 =item B<-t(able)>
702
703 Use a I<table> format for output, with wrapping of column values longer
704 than the given or determined column widths. See L<Data::ShowTable> for
705 more details.
706
707 =item B<-si(mple)>
708
709 Use a simple table format, without any wrapping of column values.
710 See L<Data::ShowTable> for more details.
711
712 =item B<-l(ist)>
713
714 Use a list style format. See L<Data::ShowTable> for more details.
715
716 =item B<-b(ox)>
717
718 Use a "boxed" style table. See L<Data::ShowTable> for more details.
719
720 =item B<-ht(ml)>
721
722 Use HTML-formating. See L<Data::ShowTable> for more details.
723
724 =item B<-ti(tles)=>I<name1>B<,>I<name2>B<,...,>I<nameN>
725
726 Define the column names explicitly. This is useful for naming columns
727 of data from C<STDIN>, when B<showtable> is being used as a filter. The
728 first column name, I<name1>, cannot begin with a digit. This option
729 allows any column titles obtained from the input to be overridden.
730
731 =item B<-noh(eaders)>
732
733 Do not output any headers on the tables; B<-titles=0> implies this option.
734
735 =item B<-f>I<n1>[,I<n2>, ..., I<nN>]
736
737 Select fields numbered I<n1>, I<n2>, etc., to display. Each I<nN> is a
738 field index, or a range of indexes in the form: C<N>-C<M> The default
739 is to show all the fields in each row. Fields are numbered from 1. An
740 example: to show the first, and three through five fields of the
741 C</etc/passwd> file:
742
743 showtable -d: -f1,2-5 /etc/passwd
744
745 =item B<-fields>=I<fname1>[,I<fname2>, ..., I<fnameN>]
746
747 Select the named fields to display. The field names must be available, either
748 through the data stream, or by using the B<-titles> option. The field
749 names given must match the existing field names I<exactly>.
750
751 Using the file C</etc/passwd> for another example: to show the same first two
752 fields, by name:
753
754 showtable -d: -titles=Login,UID -fields=Login,UID /etc/passwd
755
756 =item B<-w(idth)>=I<num>
757
758 Set the maximum table width. This value is applied to the variable
759 L<Data::Showtable::Max_Table_Width>. When the total width of all
760 columns to be displayed exceeds this value, all column widths are scaled
761 uniformly.
762
763 If B<-width> is not given, then for all output but B<-html>, the default
764 value is either "C<COLUMNS>", if defined, or 80, if not. Whith B<-html>
765 mode, there is no default value for B<-width>; in other words, there is
766 no limit to the width.
767
768 =item B<-cw(idths)>=I<w1>[,I<w2>,...,I<wN>]
769
770 Set individual column widths to the specified values. Empty column
771 widths imply no maximum width. If the B<-width> option is also given,
772 then the B<-cwidth> column widths can also be given as fractions or
773 percentages.
774
775 Example: To set the maximum width of the third column to 20 characters:
776
777 -cw=,,20
778
779 =back
780
781 =head2 B<HTML-only options> (the usage of which implies B<-html>)
782
783 =over 10
784
785 =item B<-noe(scape)>
786
787 Do not perform HTML escape sequences on the data; this allows embedded
788 HTML text in the data to be displayed properly with the B<-html> option.
789
790 =item B<-attributes>='I<attr1> I<attr2> ...'
791
792 Declare the table attributes, which are inserted into the C<TABLE>
793 token. For example, the option:
794
795 -attributes='BORDER=0 CELLSPACING=2 CELLPADDING=4'
796
797 would cause the following HTML:
798
799 <TABLE BORDER=0 CELLSPACING=2 CELLPADDING=4>
800
801 The default table attributes are:
802
803 <TABLE BORDER=1 CELLSPACING=1 CELLPADDING=1>
804
805 =item B<-t(itle)_f(ormats)>=I<fmt1>;I<fmt2>;...;I<fmtN>
806
807 Set the HTML formats for the column titles. The B<-title_formats> (or
808 just B<-tf>) can be given multiple times, for each column, or formats
809 for multiple columns can be given on the same option separated by
810 semi-colons "C<;>".
811
812 Each I<fmtN> can itself be multiple HTML items, separated by commas.
813 Each HTML element can be given either as an HTML token (eg:
814 "C<\<BOLD\>>"), or as a plain name (eg: "C<BOLD>").
815
816 For example, here is a title format specification for three columns,
817 where the first column title should be bold italic, the second italic,
818 and the third italic in a smaller font:
819
820 -tf='BOLD,I;I;<FONT SIZE=-2>,I'
821
822 =item B<-d(ata)_f(formats)>=I<fmt1>;I<fmt2>;...;I<fmtN>
823
824 The same as B<-title_formats> but applies to the column data.
825
826 =item B<-url(s)=I<col1>=I<url1>,I<col2>=I<url2>,...>
827
828 Define a mapping from column names, or indexes, to URLs to be inserted
829 as <A HREF's> around the values for the named columns. Each I<colN> is
830 a column name or index, and each I<urlN> is a string representing the
831 URL to be inserted for the given column.
832
833 The URL text may contain these substitution strings:
834
835 B<%K> - will be substituted with the current column name (or I<key>).
836
837 B<%V> - will be substituted with the current column value.
838
839 Multiple B<-url> options may be given, if desired, rather than
840 creating one long argument for a single B<-url>. For example:
841
842 showtable -d: -f1,6 -titles=Login,Homedir \
843 -url='Login=mailto:%V' \
844 -url='HomeDir=file:%V' \
845 /etc/passwd
846
847 =back
848
849 =head2 B<Other options>
850
851 =over 10
852
853 =item B<-help>
854
855 Display some help to the user and quit.
856
857 =back
858
859 =head2 B<Boxed Input>
860
861 If the input type is I<box>, then vertical and horizontal box characters
862 are removed from the input stream, and blanks surrounding the vertical
863 box characters are removed. The vertical box characters (column
864 separaters) are "C<|>" or "C<:>". The The horizontal box characters are
865 "C<+>" and "C<->".
866
867 Morever, data wrapped within a column is recognized and parsed as one
868 column value, by recognizing the presence of a I<wrapping prefix> or
869 I<wrapping suffix> character. Currently, the wrapping prefix character
870 is "<", and the wrapping suffix character is ">".
871
872 An example of data wrapped within a column is given here. The table
873 below has just two I<logical> rows of data; with both rows having data
874 wrapped into multiple I<physical> rows.
875
876 +---------+---------+---------+
877 | Col 1 | Col 2 | Col 3 |
878 +---------+---------+---------+
879 | This is>| Another>| Row 1,3>|
880 |< a cont>|< value. |<is also>|
881 |<inued >| |<long. |
882 |<value. | | |
883 |This is >| Item2-2 | Item2-3 |
884 +---------+---------+---------+
885
886 =head2 B<List Format>
887
888 When using the B<-list> or B<-input=list> options, either, or both, the
889 input and output may be in a "list" format, which is implemented
890 using the following syntax:
891
892 r1c1_name: r1c1_value
893 r1c2_name: r1c2_value
894 ...
895 r1cN_name: r1cN_value
896
897 r2c1_name: r2c1_value
898 r2c2_name: r2c2_value
899 : r2c2_value_continued
900 ...
901 r2cN_name: r2cN_value
902
903 rMc1_name: rMc1_value
904 rMc2_name: rMc2_value
905 ...
906 rMcN_name: rMcN_value
907
908 Each I<row> of data consists of one or more I<columns>, and ends with
909 a blank line.
910
911 Each I<column> consists of a I<column name>, followed by a colon ":",
912 followed by an optional, single space or tab, followed by the
913 I<column value>, on the same line.
914
915 Continuation lines of the previous column value consist of one or more
916 space or tab characters, a colon ":", one optional, single space
917 or tab, followed by the continuation value. In the example above,
918 The second column value of the second row was continued.
919
920 =head2 B<HTML Input with HTML Output>
921
922 When using B<-html> on data already containing HTML-formatted text,
923 the B<-noescape> option should be used. By default, all input
924 text is assumed I<not> to be HTML-formatted, and is escaped
925 allowing embedded "<", ">" characters, if any, to be displayed
926 correctly.
927
928 =head1 DEPENDENCIES
929
930 =over 10
931
932 =item B<Data::ShowTable> module
933
934 Performs the actual output formatting.
935
936 =back
937
938 =head1 AUTHOR
939
940 Alan K. Stebbens I<[email protected]>
941
942 =head1 BUGS
943
944 =over 5
945
946 =item *
947
948 Currently, the box formatting characters are not configurable: '+' for
949 the corners; '-' and '|' for the tops and sides, respectively. In an
950 ideal world, these things would be configurable.
951
952 =item *
953
954 The continuation prefix and suffix characters, '<' and '>',
955 respectively, are also not configurable:
956
957 =item *
958
959 When reading I<table> input, any data ending with ">" will
960 be considered to be continued by the next row of data. To avoid
961 this, use B<-input=simple>.
962
963 =item *
964
965 When selecting noncontiguous fields (ie: B<-f1,4>>) without
966 field names, the default field names will be consecutively
967 numbered from 1, which is counter-intuitive to the original
968 selection. To avoid this, name the fields using the B<-title=...>
969 option.
970
971 =back
972
973 =cut