ShowTable - routines to display tabular data in several formats.
use Data::ShowTable;
ShowTable { parameter => value, ... };
ShowTable \@titles, \@types, \@widths, \&row_sub [, \&fmt_sub ];
ShowDatabases \@dbnames;
ShowDatabases { parameter => value, ... };
ShowTables \@tblnames;
ShowTables { parameter => value, ... };
ShowColumns \@columns, \@col_types, \@col_lengths, \@col_attrs;
ShowColumns { parameter => value, ... };
ShowBoxTable \@titles, \@types, \@widths, \&row_sub [, \&fmt_sub ];
ShowBoxTable { parameter => value, ... };
ShowSimpleTable \@titles, \@types, \@widths, \&row_sub [, \&fmt_sub];
ShowSimpleTable { parameter => value, ... };
ShowHTMLTable \@titles, \@types, \@widths, \&row_sub [, \&fmt_sub];
ShowHTMLTable { parameter => value, ... };
ShowListTable \@titles, \@types, \@widths, \&row_sub [, \&fmt_sub];
ShowListTable { parameter => value, ... };
package Data::ShowTable
;
$Show_Mode = 'mode';
$Max_Table_Width = number;
$Max_List_Width = number;
$No_Escape = flag;
%URL_Keys = { "$colname" => "$col_URL", ... };
@Title_Formats = ( fmt1_html, <fmt2_html>, ... );
@Data_Formats = ( fmt1_html, <fmt2_html>, ... );
ShowRow $rewindflag, \$index, $col_array_1 [, $col_array_2, ...;]
$fmt = ShowTableValue $value, $type, $max_width, $width, $precision, $showmode;
[$plaintext = ] PlainText [$htmltext];
The ShowTable module provides subroutines to display tabular data, typially from a database, in nicely formatted columns, in several formats. Its arguments can either be given in a fixed order, or, as a single, anonymous hash-array.
The output format for any one invocation can be one of four possible styles:
+
", "-
", and "|
" characters. See "ShowBoxTable" for details.
The subroutines which perform these displays are listed below.
This module exports the following subroutines:
ShowDatabases - show list of databases ShowTables - show list of tables ShowColumns - show table of column info ShowTable - show a table of data ShowRow - show a row from one or more columns ShowTableValue - show a single column's value ShowBoxTable - show a table of data in a box ShowListTable - show a table of data in a list ShowSimpleTable - show a table of data in a simple table ShowHTMLTable - show a table of data using HTML PlainText - convert HTML text into plain text
All of these subroutines, and others, are described in detail in the following sections.
Format and display the contents of one or more rows of data.
ShowTable { parameter => value, ... };
ShowTable \@titles, \@types, \@widths, \&row_sub [, \&fmt_sub [, $max_width ] [, $show_mode ] ];
The ShowTable subroutine displays tabular data aligned in columns, with headers. ShowTable supports four modes of display: Box, Table, List, and HTML. Each mode is described separately below.
The arguments to ShowTable may be given in one of two ways: as a hashed-array, or by a combination of fixed order arguments, and some package-global variable settings. The hash-array parameters correspond to the fixed arguments and the global-parameter settings.
In the list below, both the hash-array parameter name and the fixed-order argument name is given as the value. In the case where there is no fixed-order argument for a given parameter-value pair, then the corresponding global variable name is given.
titles
=> \@titles
Field_num
is used by default. To have a column
have no title, use the empty string.
types
=> \@types
/text|char|string/i
", then the column
alignment will be left-justified, otherwise it will be right-justified.
widths
=> \@widths
row_sub
=> \&row_sub
A reference to a subroutine which successively returns rows of values in an array. It is called for two purposes, each described separately:
* To fetch successive rows of data:
@row = &$row_sub(0);
When given a null, zero, or empty argument, the next row is returned.
* To initialize or rewind the data traversal.
$rewindable = &$row_sub(1);
When invoked with a non-null argument, the subroutine should rewind its row pointer to start at the first row of data. If the data which row_sub is traversing is not rewindable, it must return zero or null. If the data is rewindable, a non-null, non-zero value should be returned.
The row_sub must expect to be invoked once with a non-null argument, in order to discover whether or not the data is rewindable. If the data cannot be rewound, row_sub will thereafter only be called with a zero argument.
Specifically, row_sub subroutine is used in this manner:
$rewindable = &$row_sub(1); if ($rewindable) { while ((@row = &$row_sub(0)), $#row >= 0) { # examine lengths for optimal formatting } &$row_sub(1); # rewind } while ((@row = &$row_sub(0)), $#row >= 0) { # format the data }
The consequence of data that is not rewindable, a reasonably nice table will still be formatted, but it may contain fairly large amounts of whitespace for wide columns.
fmtsub
=> \&fmt_sub
A reference to a subroutine which formats a value, according to its type, width, precision, and the current column width. It is invoked either with a fixed list of arguments, or with a hash-array of parameter and value pairs.
$string = &fmt_sub { I<parameter> => I<value>, ... }; $string = &fmt_sub($value, $type, $max_width, $width, $precision)
If \&fmt_sub is omitted, then a default subroutine, ShowTableValue, will be used, which will use Perl's standard string formatting rules.
The arguments to \&fmt_sub, either as values passed in a fixed order, or as part of the parameter value pair, are described in the section on "ShowTableValue below.
max_width
=> number,
show_mode
=> 'mode',
'Box'
,
'Table'
, 'Simple'
, 'List'
, and 'HTML'
.
Show a list of database names.
ShowDatabases \@dbnames;
ShowDatabases { 'data' => \@dbnames, parameter => value, ...};
ShowDatabases is intended to be used to display a list of database names, under the column heading of "Databases". It is a special case usage of ShowTable (and can thus be passed any parameter suitable for ShowTable.
The argument, \@dbnames, is a reference to an array of strings, used as the values of the single column display.
Show an array of table names.
ShowTables \@tblnames;
ShowTables { 'data' => \@tblnames, parameter => value, ...};
ShowTables is used to display a list of table names, under the column heading of "Tables". It is a special case usage of ShowTable, and can be passed any "ShowTable" argument parameter.
Display a table of column names, types, and attributes.
ShowColumns { parameter => values, ... };
ShowColumns \@columns, \@col_types, \@col_lengths, \@col_attrs;
The ShowColumns subroutine displays a table of column names, types, lengths, and other attributes in a nicely formatted table. It is a special case usage of ShowTable, and can be passed any argument suitable for "ShowTable";
The arguments are:
columns
= \@columns
col_types
= \@col_types
col_lengths
= \@col_lengths
col_attrs
= \@col_attrs
The columns, types, lengths, and attributes are displayed in a table with the column headings: "Column", "Type", "Length", and "Attributes". This is a special case usage of ShowTable, and can be passed additional arguments suitable for "ShowTable".
Show tabular data in a box.
ShowBoxTable { parameter = value, ... };
ShowBoxTable \@titles, \@types, \@widths, \&row_sub [, [ \&fmt_sub ] [, $max_width ] ];
The ShowBoxTable displays tabular data in titled columns using a "box" of ASCII graphics, looking something like this:
+------------+----------+-----+----------+ | Column1 | Column2 | ... | ColumnN | +------------+----------+-----+----------+ | Value11 | Value12 | ... | Value 1M | | Value21 | Value22 | ... | Value 2M | | Value31 | Value32 | ... | Value 3M | | ... | ... | ... | ... | | ValueN1 | ValueN2 | ... | Value NM | +------------+----------+-----+----------+
The arguments are the same as with "ShowTable". If the @titles array is empty, the header row is omitted.
Display a table of data using a simple table format.
ShowSimpleTable \@titles, \@types, \@widths, \&row_sub [, \&fmt_sub];
ShowSimpleTable { parameter => values, ... };
The ShowSimpleTable subroutine formats data into a simple table of aligned columns, in the following example:
Column1 Column2 Column3 ------- ------- ------- Value1 Value2 Value3 Value12 Value22 Value32
Columns are auto-sized by the data's widths, plus two spaces between columns. Values which are too long for the maximum colulmn width are wrapped within the column.
Display a table of data nicely using HTML tables.
ShowHTMLTable { parameter => value, ... };
ShowHTMLTable \@titles, \@types, \@widths, \&row_sub [, \&fmt_sub [, $max_width [, \%URL_Keys [, $no_escape [, \@title_formats [, \@data_formats [, $table_attrs ] ] ] ] ] ] ];
The ShowHTMLTable displays one or more rows of columns of data using
the HTML \<TABLE\
> feature. In addition to the usual parameter arguments
of "ShowTable", the following parameter arguments are defined:
url_keys
=> \%URL_Keys,
This is a hash array of column names (titles) and corresponding base URLs. The values of any column names or indexes occuring as keys in the hash array will be generated as hypertext anchors using the associated printf-like string as the base URL. Either the column name or the column index (beginning with 1) may be used as the hash key.
In the string value, these macros can be substituted:
"%K
" is replaced with the column name.
"%V
" is replaced with the column value;
"%I
" is replaced with the column index.
For example, if we define the array:
$base_url = "http://www.$domain/cgi/lookup?col=%K?val=%V"; %url_cols = ('Author' => $base_url, 'Name' => $base_url);
Then, the values in the Author
column will be generated with the following
HTML text:
<A HREF="http://www.$domain/cgi/lookup?col=Author?val=somevalue>somevalue</A>
and the values in the Name
column will be generated with the URL:
<A HREF="http://www.$domain/cgi/lookup?col=Name?val=othervalue>othervalue</A>
If this variable is not given, it will default to the global variable
\%URL_Keys
.
no_escape
=> boolean,
Unless $no_escape is set, HTML-escaping is performed on the data values in order to properly display the special HTML formatting characters : '\<', '\>', and '&'. If you wish to display data with embedded HTML text, you must set $no_escape.
Enabling embedded HTML, turns on certain heuristics which enable the
user to more completely define appearance of the table. For instance,
any \<TR\
> tokens found embedded *anywhere* within a row of data will
be placed at the front of the row, within the generated \<TR\
>.
Similarly, a row of data containing the \<THEAD\
> or \<TFOOT\
>
tokens, and their closing counterparts, will begin and end, respectively
a table header or footer data.
title_formats
=> \@title_formats,
tformats
=> \@title_formats,
An array of HTML formatting elements for the column titles, one for each
column. Each array element is a list of one or more HTML elements,
given as \<ELEMENT\
> or plainly, ELEMENT
, and separated by a comma
','
, semi-colon ';'
, or vertical bar '|'
. Each given HTML
element is prepended to the corresponding column title, in the order
given. The corresponding HTML closing elements are appended in the
opposite order.
For example, if \@title_formats contains the two elements:
[ 'FONT SIZE=+2,BOLD', 'FONT COLOR=red,EM' ]
then the text output for the title of the first column would be:
<FONT SIZE=+2><BOLD>I<column_1_title></BOLD></FONT>
If title_formats
is omitted, the global variable @Title_Formats
is used by default.
data_formats
=> \@data_formats,
dformats
=> \@data_formats,
title_formats
, this array provides HTML formatting for
the columns of each row of data. If data_formats
is omitted or
null, then the global variable \@Data_Formats is used by default.
table_attrs
=> $table_attrs,
This variable defines a string of attributes to be inserted within the
\<TABLE\
> token. For example, if the user wishes to have no table
border:
ShowHTMLTable { ... table_attrs => 'BORDER=0', ... };
Display a table of data using a list format.
ShowListTable { parameter => value, ... };
ShowListTable \@titles, \@types, \@widths, \&row_sub [, \&fmt_sub [, $max_width [, $wrap_margin ] ] ];
The arguments for ShowListTable are the same as for "ShowTable", except for those described next.
max_width
= number,
wrap_margin
= number,
Lines are truncated, and wrapped when their length exceeds $max_width. Wrapping is done on a word-basis, unless the resulting right margin exceeds $wrap_margin, in which case the line is simply truncated at the $max_width limit.
The $max_width variable defaults to $Max_List_Width. The $wrap_margin defaults to $List_Wrap_Margin.
In List mode, columns (called "fields" in List mode) are displayed wth a field name and value pair per line, with records being one or more fields . In other words, the output of a table would look something like this:
Field1_1: Value1_1 Field1_2: Value1_2 Field1_3: Value1_3 ... Field1-N: Value1_M <empty line> Field2_1: Value2_1 Field2_2: Value2_2 Field2_3: Value2_3 ... Field2_N: Value2_N ... FieldM_1: ValueM_1 FieldM_2: ValueM_2 ... FieldM_N: ValueM_N <empty line> <empty line>
Characteristics of List mode:
A long line can be continue by a null field (column):
Field2: blah blah blah : blah blah blah
Field_
NN" are used
instead.
Fetch rows successively from one or more columns of data.
ShowRow $rewindflag, \$index, $col_array_1 [, $col_array_2, ...;]
The ShowRow subroutine returns a row of data from one or more columns of data. It is designed to be used as a callback routine, within the ShowTable routine. It can be used to select elements from one or more array reference arguments.
If passed two or more array references as arguments, elements of the arrays selected by $index are returned as the "row" of data.
If a single array argument is passed, and each element of the array is itself an array, the subarray is returned as the "row" of data.
If the $rewindflag flag is set, then the $index pointer is reset to zero, and "true" is returned (a scalar 1). This indicates that the data is rewindable to the ShowTable routines.
When the $rewindflag is not set, then the current row of data, as determined by $index is returned, and $index will have been incremented.
An actual invocation (from ShowColumns) is:
ShowTable \@titles, \@types, \@lengths, sub { &ShowRow( $_[0], \$current_row, $col_names, $col_types, $col_lengths, \@col_attrs); };
In the example above, after each invocation, the $current_row argument will have been incremented.
Prepare and return a formatted representation of a value. A value argument, using its corresponding type, effective width, and precision is formatted into a field of a given maximum width.
$fmt = ShowTableValue $value, $type, $max_width, $width, $precision, $showmode;
width
=> $width
precision
=> $precision
value
=> $value
char
, varchar
, int
, etc.
maxwidth
=> $max_width
$plaintext = &PlainText($htmltext);
&PlainText
This function removes any HTML formatting sequences from the input argument,
or from $_
if no argument is given. The resulting plain text is returned
as the result.
The following variables may be set by the user to affect the display (with the defaults enclosed in square brackets [..]):
$ENV{'SHOW_MODE'}
, is used when this variable is
null or the empty string. The possible values for this variable are:
"Box"
, "List"
, "Table"
, and "HTML"
. Case is insignificant.
$ENV{'COLUMNS'}
, is
used to define this value when it is null.
my $args = &get_params \@argv, \%params, \@arglist;
Given the @argv originally passed to the calling sub, and the hash of named parameters as %params, and the array of parameter names in the order expected for a pass-by-value invocation, set the values of each of the variables named in @vars.
If the only element of the @argv is a hash array, then set the variables to the values of their corresponding parameters used as keys to the hash array. If the parameter is not a key of the %params hash, and is not a key in the global hash %ShowTableParams, then an error is noted.
When @argv has multiple elements, or is not a hash array, set each variable, in the order given within @arglist, to the values from the @argv, setting the variables named by each value in %params.
Variables may given either by name or by reference.
The result is a HASH array reference, either corresponding directly to the HASH array passed as the single argument, or one created by associating the resulting variable values to the parameter names associated with the variable names.
($prefixes,$suffixes) = html_formats \@html_formats;
The html_format function takes an array reference of HTML formatting elements \@html_formats, and builds two arrays of strings: the first: $prefixes, is an array of prefixes containing the corresponding HTML formatting elements from \@html_formats, and the second, $suffixes, containing the appropriate HTML closing elements, in the opposite order.
The result is designed to be used as prefixes and suffixes for the corresponding titles and column values.
The array \@html_formats contains lists of HTML formatting elements,
one for each column (either title or data). Each array element is a
list of one or more HTML elements, either given in HTML syntax, or as a
"plain" name (ie: given as \<ELEMENT\
> or plainly, ELEMENT
).
Multiple elements are separated by a comma ','
.
The resulting array of $prefixes contains the corresponding opening elements, in the order given, with the proper HTML element syntax. The resulting array of $suffixes contains the closing elements, in the opposite order given, with the proper HTML element syntax.
For example, if \@html_formats contains the two elements:
[ 'FONT SIZE=+2,BOLD', 'FONT COLOR=red,EM' ]
then the resulting two arrays will be returned as:
[ [ '<FONT SIZE=+2><BOLD>', '<FONT COLOR=red><EM>' ], [ '</FONT></BOLD>', '</FONT></EM>' ] ]
($num_cols, $widths, $precision, $max_widths) = &calc_widths( $widthspec, $titles, $rewindable, $row_sub, $fmt_sub, $types, $showmode, $max_width);
calc_widths is a generalized subroutine used by all the ShowTable variant subroutines to setup internal variables prior to formatting for display. Calc_widths handles the column width and precision analysis, including scanning the data (if rewindable) for appropriate default values.
The number of columns in the data is returned, as well as three arrays: the declared column widths, the column precision values, and the maximum column widths.
is the ref to the array of maximum widths for the given columns.
A reference to an array of column width (or length) values, each given as an integer, real number, or a string value of "width.precision". If a value is zero or null, the length of the corresponding formatted data (if rewindable) and column title length are used to determine a reasonable default.
If a column's width portion is a positive, non-zero number, then the column will be this wide, regardless of the values lengths of the data in the column.
If the column's width portion is given as a negative number, then the positive value is used as a minimum column width, with no limit on the maximum column width. In other words, the column will be at least width characters wide.
If the data is not rewindable, and a column's width value is null or zero, then the length of the column title is used. This may cause severe wrapping of data in the column, if the column data lengths are much greater than the column title widths.
$titles
array is empty, then the $widthspec
array is used to
determine the default number of columns.
A flag indicating whether or not the data being formatted is rewindable. If this is true, a pass over the data will be done in order to calculate the maximum lengths of the actual formatted data, using $fmt_sub (below), rather than just rely on the declared column lengths. This allows for optimal column width adjustments (ie: the actual column widths may be less than the declared column widths).
If it is not desired to have the column widths dynamically adjusted, then set the $rewindable argument to 0, even if the data is rewindable.
box
", "table
", "list
", and "html
". Used to adjust widths
for formatting requirements.
$wrapped = &putcell( \@cells, $c, $cell_width, \@prefix, \@suffix, $wrap_flag );
Output the contents of an array cell at $cell[$c], causing text longer than $cell_width to be saved for output on subsequent calls. Prefixing the output of each cell's value is a string from the two-element array @prefix. Suffixing each cell's value is a string from the two-element array @suffix. The first element of either array is selected when $wrap_flag is zero or null, or when there is no more text in the current to be output. The second element is selected when $wrap_flag is non-zero, and when there is more text in the current cell to be output.
In the case of text longer than $cell_width, a non-zero value is returned.
Cells with undefined data are not output, nor are the prefix or suffix strings.
Center a string within a given width.
$field = center $string, $width;
Compute the maximum value from a list of values.
$max = &max( @values );
Compute the minum value from a list of values.
$min = &min( @values );
Compute the maximum length of a set of strings in an array reference.
$maxlength = &max_length( \@array_ref );
Translate regular text for output into an HTML document. This means certain characters, such as "&", ">", and "<" must be escaped.
$output = &htmltext( $input [, $allflag ] );
If $allflag is non-zero, then all characters are escaped. Normally, only the four HTML syntactic break characters are escaped.
Print text followed by a newline.
out $fmt [, @text ];
Print text (without a trailing newline).
out $fmt [, @text ];
Alan K. Stebbens <aks@sgi.com>
Embedded HTML is how the user can insert formatting overrides. However, the HTML formatting techniques have not been given much consideration -- feel free to provide constructive feedback.