Text::Table(3pm)
π NAME π
Okay bestie, meet Text::Table β Organize Data in Tables. In manual-page land this is Text::Table(3pm), and it is literally here to make your data look organized instead of chaotic. β¨
π VERSION π
version 1.135 β no cap, that's the version. π
π¦ SYNOPSIS π¦
use Text::Table;
my $tb = Text::Table->new(
"Planet", "Radius\nkm", "Density\ng/cm^3"
);
$tb->load(
[ "Mercury", 2360, 3.7 ],
[ "Venus", 6110, 5.1 ],
[ "Earth", 6378, 5.52 ],
[ "Jupiter", 71030, 1.3 ],
);
print $tb;
That prints a table from the given title and data, and it looks like this:
Planet Radius Density
km g/cm^3
Mercury 2360 3.7
Venus 6110 5.1
Earth 6378 5.52
Jupiter 71030 1.3
Notice that two-line titles work, and that the planet names are aligned differently than the numbers. πͺ
πΈ DESCRIPTION πΈ
Organization of data in table form is a time-honored and useful method of data representation. While columns of data are trivially generated by computer through formatted output, even simple tasks like keeping titles aligned with the data columns are not trivial, and the one-shot solutions one comes up with tend to be particularly hard to maintain. Text::Table allows you to create and maintain tables that adapt to alignment requirements as you use them. π
π§ Overview π§
The process is simple: you create a table (a Text::Table object) by describing the columns the table is going to have. Then you load lines of data into the table, and finally print the resulting output lines. Alignment of data and column titles is handled dynamically in dependence on the data present. β¨
π Table Creation π
- In the simplest case, if all you want is a number of (untitled) columns, you create an unspecified table and start adding data to it. The number of columns is taken from the first line of data.
- To specify a table you specify its columns. A column description can contain a title and alignment requirements for the data, both optional. Additionally, you can specify how the title is aligned with the body of a column, and how the lines of a multiline title are aligned among themselves.
- The columns are collected in the table in the order they are given. On data entry, each column corresponds to one data item, and in column selection columns are indexed left to right, starting from
0. - Each title can be a multiline string which will be blank-filled to the length of the longest partial line. The largest number of title lines in a column determines how many title lines the table has as a whole, including the case that no column has any titles.
- On output, columns are separated by a single blank. You can control what goes between columns by specifying separators between (or before, or after) columns. Separators don't contain any data and don't count in column indexing. They also don't accumulate: in a sequence of only separators and no columns, only the last one counts.
π₯ Status Information π₯
The width (in characters), height (in lines), number of columns, and similar data about the table is available. π
π Data Loading π
Table data is entered line-wise, each time specifying data entries for all table columns. A bulk loader for many lines at once is also available. You can clear the data from the table for re-use (though you will more likely just create another table). π«Ά
Data can contain colorizing escape sequences (as provided by Term::AnsiColor) without upsetting the alignment. π
π Table Output π
The output area of a table is divided in the title and the body. π
The title contains the combined titles from the table columns, if any. Its content never changes with a given table, but it may be spread out differently on the page through alignment with the data.
The body contains the data lines, aligned column-wise as specified, and left-aligned with the column title.
Each of these is arranged like a Perl array (counting from 0) and can be accessed in portions by specifying a first line and the number of following lines. Also like an array, giving a negative first line counts from the end of the area. The whole table, the title followed by the body, can also be accessed in this manner.
The subdivisions are there so you can repeat the title (or parts of it) along with parts of the body on output, whether for screen paging or printout. π
A rule line is also available, which is the horizontal counterpart to the separator columns you specify with the table. It is basically a table line as it would appear if all data entries in the line were empty, that is, a blank line except for where the column separators have non-blank entries. If you print it between data lines, it will not disrupt the vertical separator structure as a plain blank line would. You can also request a solid rule consisting of any character, and even one with the non-blank column separators replaced by a character of your choice. This way you can get the popular representation of line-crossings like so:
|
----+---
|
π§ Warning Control π§
On table creation, some parameters are checked and warnings issued if you allow warnings. You can also turn warnings into fatal errors. π
π VERSION π
version 1.135 π
π SPECIFICATIONS π
π Column Specification π
Okay so, each column specification is a single scalar, no cap. Columns can be either proper data columns or column separators, and both can be specified either as (possibly multi-line) strings or in a more explicit form as hash-refs. In the string form, proper columns are given as plain strings, and separators are given as scalar references to strings. In hash form, separators have a true value in the field "is_sep" while proper columns don't have this field. Slay, that's the whole vibe check. β¨
π Columns as strings
A column is given as a column title (any number of lines), optionally followed by alignment requirements. Alignment requirements start with a line that begins with an ampersand "&". However, only the last such line counts as such, so if you have title lines that begin with "&", just append an ampersand on a line by itself as a dummy alignment section if you don't have one anyway. Bestie, that's the trick. π
What follows the ampersand on its line is the alignment style (like left, right, ... as described in "Alignment"), you want for the data in this column. If nothing follows, the general default auto is used. If you specify an invalid alignment style, it falls back to left alignment. Not me warning youβit's literally in the specs. π
The lines that follow can contain sample data for this column. These are considered for alignment in the column, but never actually appear in the output. The effect is to guarantee a minimum width for the column even if the current data doesn't require it. This helps dampen the oscillations in the appearance of dynamically aligned tables. Iconic behavior, honestly. π¦
π§ Columns as Hashes
The format is:
{
title => $title,
align => $align,
sample => $sample,
align_title => $align_title,
align_title_lines => $align_title_lines,
}
$title contains the title lines and $sample the sample data. Both can be given as a string or as an array-ref to the list of lines. $align contains the alignment style (without a leading ampersand), usually as a string. You can also give a regular expression here, which specifies regex alignment. A regex can only be specified in the hash form of a column specification. π
In hash form you can also specify how the title of a column is aligned with its body. To do this, you specify the keyword "align_title" with "left", "right" or "center". Other alignment specifications are not valid here. The default is "left". π«Ά
"align_title" also specifies how the lines of a multiline title are aligned among themselves. If you want a different alignment, you can specify it with the key "align_title_lines". Again, only "left", "right" or "center" are allowed. πΈ
Do not put other keys than those mentioned above (title, align, align_title, align_title_lines, and sample) into a hash that specifies a column. Most would be ignored, but some would confuse the interpreter (in particular, is_sep has to be avoided). Like, please don't do it. π
π Separators as strings
A separator must be given as a reference to a string (often a literal, like "\' | '"), any string that is given directly describes a column. So yes, the reference is the whole point. π₯
It is usually just a (short) string that will be printed between table columns on all table lines instead of the default single blank. If you specify two separators (on two lines), the first one will be used in the title and the other in the body of the table. Cute, right? π
π Separators as Hashes
The hash representation of a separator has the format:
{
is_sep => 1,
title => $title,
body => $body,
}
$title is the separator to be used in the title area and $body the one for the body. If only one is given, it will be used for both. If none is given, a blank is used. If one is shorter than the other, it is blank filled on the right. π
The value of "is_sep" must be set to a true value, this is the distinguishing feature of a separator. That's the main character energy of this whole hash. π
π Alignment π
The original documentation to Text::Aligner contains all the details on alignment specification, but here is the rundown: π«
The possible alignment specifications are left, right, center, num and point (which are synonyms), and auto. The first three explain themselves. β¨
num (and point) align the decimal point in the data, which is assumed to the right if none is present. Strings that aren't numbers are treated the same way, that is, they appear aligned with the integers unless they contain a ".". Instead of the decimal point ".", you can also specify any other string in the form num(,), for instance. The string in parentheses is aligned in the data. The synonym point for num may be more appropriate in contexts that deal with arbitrary strings, as in point(=>) (which might be used to align certain bits of Perl code). Obsessed with a flexible alignment point, ngl. π¦
regex alignment is a more sophisticated form of point alignment. If you specify a regular expression, as delivered by qr//, the start of the match is used as the alignment point. If the regex contains capturing parentheses, the last submatch counts. [The usefulness of this feature is under consideration.] π
auto alignment combines numeric alignment with left alignment. Data items that look like numbers, and those that don't, form two virtual columns and are aligned accordingly: "num" for numbers and "left" for other strings. These columns are left-aligned with each other (i.e. the narrower one is blank-filled) to form the final alignment. π
This way, a column that happens to have only numbers in the data gets num alignment, a column with no numbers appears left-aligned, and mixed data is presented in a reasonable way. Honestly? Very slay. π
π¦ Column Selection π¦
Besides creating tables from scratch, they can be created by selecting columns from an existing table. Tables created this way contain the data from the columns they were built from. It's giving remix, but make it data. π
This is done by specifying the columns to select by their index (where negative indices count backward from the last column). The same column can be selected more than once and the sequence of columns can be arbitrarily changed. Separators don't travel with columns, but can be specified between the columns at selection time. Periodt. π
You can make the selection of one or more columns dependent on the data content of one of them. If you specify some of the columns in angle brackets [...], the whole group is only included in the selection if the first column in the group contains any data that evaluates to boolean true. That way you can de-select parts of a table if it contains no interesting data. Any column separators given in brackets are selected or deselected along with the rest of it. Bestie, that's conditional column selection and it eats. π₯
π PUBLIC METHODS π
Okay bestie, this is the main-character section where the table actually does stuff. Slay.
β¨ Table Creation β¨
πΈ new() πΈ
my $tb = Text::Table->new( $column, ... );
Creates a table with the columns you specify. A column can be a proper column that contains and displays data, or a separator that tells the table how to fill the space between columns. The parameter format is described under "Column Specification". Specifying an invalid alignment for a column results in a warning, if these are allowed.
If no columns are specified, the number of columns is taken from the first line of data added to the table. The effect is as if you had specified Text::Table->new( ( '') x $n), where $n is the number of columns.
π¦ select() π¦
my $sub = $tb->select( $column, ...);
Creates a table from the listed columns of the table $tb, including the data. Columns are specified as integer indices which refer to the data columns of $tb. Columns can be repeated and specified in any order. Negative indices count from the last column. If an invalid index is specified, a warning is issued, if allowed.
As with new(), separators can be interspersed among the column indices and will be used between the columns of the new table.
If you enclose some of the arguments (column indices or separators) in brackets [ ... ] (technically, you specify them inside an arrayref), they form a group for conditional selection. The group is only included in the resulting table if the first actual column inside the group contains any data that evaluate to a boolean true. This way you can exclude groups of columns that wouldn't contribute anything interesting. Note that separators are selected and de-selected with their group. That way, more than one separator can appear between adjacent columns. They don't add up, but only the rightmost separator is used. A group that contains only separators is never selected. [Another feature whose usefulness is under consideration.]
β Status Information β
π n_cols() π
$tb->n_cols
Returns the number of columns in the table.
π width() π
$tb->width
Returns the width (in characters) of the table. All table lines have this length (not counting a final "\n" in the line), as well as the separator lines returned by $tb->rule() and $b->body_rule(). The width of a table can potentially be influenced by any data item in it.
π height() π
$tb->height
Returns the total number of lines in a table, including title lines and body lines. For orthogonality, the synonym table_height() also exists.
π table_height() π
Same as $table->height().
π title_height() π
$tb->title_height
Returns the number of title lines in a table.
π«Ά body_height() π«Ά
$tb->body_height
Returns the number of lines in the table body.
π§ colrange() π§
$tb->colrange( $i)
Returns the start position and width of the $i-th column (counting from 0) of the table. If $i is negative, counts from the end of the table. If $i is larger than the greatest column index, an imaginary column of width 0 is assumed right of the table.
π Data Loading π
π add() π
$tb->add( $col1, ..., $colN)
Adds a data line to the table, returns the table.
$col1, ..., $colN are scalars that correspond to the table columns. Undefined entries are converted to '', and extra data beyond the number of table columns is ignored.
Data entries can be multi-line strings. The partial strings all go into the same column. The corresponding fields of other columns remain empty unless there is another multi-line entry in that column that fills the fields. Adding a line with multi-line entries is equivalent to adding multiple lines.
Every call to add() increases the body height of the table by the number of effective lines, one in the absence of multiline entries.
π load() π
$tb->load( $line, ...)
Loads the data lines given into the table, returns the table.
Every argument to load() represents a data line to be added to the table. The line can be given as an array(ref) containing the data items, or as a string, which is split on whitespace to retrieve the data. If an undefined argument is given, it is treated as an empty line.
π§Ό clear() π§Ό
$tb->clear;
Deletes all data from the table and resets it to the state after creation. Returns the table. The body height of a table is 0 after clear().
π Table Output π
The three methods table(), title(), and body() are very similar. They access different parts of the printable output lines of a table with similar methods. The details are described with the table() method.
π table() π
The table() method returns lines from the entire table, starting with the first title line and ending with the last body line.
In array context, the lines are returned separately, in scalar context they are joined together in a single string.
my @lines = $tb->table;
my $line = $tb->table( $line_number);
my @lines = $tb->table( $line_number, $n);
The first call returns all the lines in the table. The second call returns one line given by $line_number. The third call returns $n lines, starting with $line_number. If $line_number is negative, it counts from the end of the array. Unlike the select() method, table() (and its sister methods title() and body()) is protected against large negative line numbers, it truncates the range described by $line_number and $n to the existing lines. If $n is 0 or negative, no lines are returned (an empty string in scalar context).
πͺ stringify() πͺ
Returns a string representation of the table. This method is called for stringification by overload.
my @table_strings = map { $_->stringify() } @tables;
π title() π
Returns lines from the title area of a table, where the column titles are rendered. Parameters and response to context are as with table(), but no lines are returned from outside the title area.
π«Ά body() π«Ά
Returns lines from the body area of a table, that is the part where the data content is rendered, so that $tb->body( 0) is the first data line. Parameters and response to context are as with table().
π οΈ rule() π οΈ
$tb->rule;
$tb->rule( $char);
$tb->rule( $char, $char1);
$tb->rule( sub { my ($index, $len) = @_; },
sub { my ($index, $len) = @_; },
);
Returns a rule for the table.
A rule is a line of table width that can be used between table lines to provide visual horizontal divisions, much like column separators provide vertical visual divisions. In its basic form (returned by the first call) it looks like a table line with no data, hence a blank line except for the non-blank parts of any column-separators. If one character is specified (the second call), it replaces the blanks in the first form, but non-blank column separators are retained. If a second character is specified, it replaces the non-blank parts of the separators. So specifying the same character twice gives a solid line of table width. Another useful combo is $tb->rule( '-', '+'), together with separators that contain a single nonblank "|", for a popular representation of line crossings.
rule() uses the column separators for the title section if there is a difference.
If callbacks are specified instead of the characters, then they receive the index of the section of the rule they need to render and its desired length in characters, and should return the string to put there. The indexes given are 0 based (where 0 is either the left column separator or the leftmost cell) and the strings will be trimmed or extended in the replacement.
π§ body_rule() π§
body_rule() works like rule(), except the rule is generated using the column separators for the table body.
π¨ Warning Control π¨
π
warnings() π
Text::Table->warnings();
Text::Table->warnings( 'on');
Text::Table->warnings( 'off'):
Text::Table->warnings( 'fatal'):
The warnings() method is used to control the appearance of warning messages while tables are manipulated. When Text::Table starts, warnings are disabled. The default action of warnings() is to turn warnings on. The other possible arguments are self-explanatory. warnings() can also be called as an object method ("$tb->warnings( ...)").
π VERSION π
This document pertains to Text::Table version 1.127.
π BUGS π
- auto alignment doesn't support alternative characters for the decimal point. This is actually a bug in the underlying Text::Aligner by the same author.
π AUTHOR π
π MAINTAINER π
Shlomi Fish, <http://www.shlomifish.org/> β CPAN ID: "SHLOMIF".
πΈ ORIGINAL AUTHOR πΈ
Anno Siegel CPAN ID: ANNO siegel@zrz.tu-berlin.de http://www.tu-berlin.de/~siegel
π COPYRIGHT π
Copyright (c) 2002 Anno Siegel. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the ISC license.
(This program had been licensed under the same terms as Perl itself up to version 1.118 released on 2011, and was relicensed by permission of its originator).
The full text of the license can be found in the LICENSE file included with this module.
π¦ SEE ALSO π¦
- Text::Table::Tiny supports a simple model for generating text tables, with some flexibility on the look of the table.
- Text::Table::Manifold provides a much richer interface for defining tables. The SEE ALSO section of its documentation lists a lot more table modules on CPAN.
- Text::Aligner can be used to align text on a line-by-line basis.
β¨ EXAMPLES β¨
π center align and Unicode output
okay bestie, this example is literally the whole point β center-aligned column, pretty Unicode box-drawing, the works. behold:
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use Text::Table ();
binmode STDOUT, ':encoding(utf8)';
my @cols = qw/First Last/;
push @cols,
+{
title => "Country",
align => "center",
};
my $sep = \'β';
my $major_sep = \'β';
my $tb = Text::Table->new( $sep, " Number ", $major_sep,
( map { +( ( ref($_) ? $_ : " $_ " ), $sep ) } @cols ) );
my $num_cols = @cols;
$tb->load( [ 1, "Mark", "Twain", "USA", ] );
$tb->load( [ 2, "Charles", "Dickens", "Great Britain", ] );
$tb->load( [ 3, "Jules", "Verne", "France", ] );
my $make_rule = sub {
my ($args) = @_;
my $left = $args->{left};
my $right = $args->{right};
my $main_left = $args->{main_left};
my $middle = $args->{middle};
return $tb->rule(
sub {
my ( $index, $len ) = @_;
return ( 'β' x $len );
},
sub {
my ( $index, $len ) = @_;
my $char = (
( $index == 0 ) ? $left
: ( $index == 1 ) ? $main_left
: ( $index == $num_cols + 1 ) ? $right
: $middle
);
return $char x $len;
},
);
};
my $start_rule = $make_rule->(
{
left => 'β',
main_left => 'β₯',
right => 'β',
middle => 'β¬',
}
);
my $mid_rule = $make_rule->(
{
left => 'β',
main_left => 'β«',
right => 'β€',
middle => 'βΌ',
}
);
my $end_rule = $make_rule->(
{
left => 'β',
main_left => 'β¨',
right => 'β',
middle => 'β΄',
}
);
print $start_rule, $tb->title,
( map { $mid_rule, $_, } $tb->body() ), $end_rule;
and it emits this exact output β no cap, it's giving museum-quality:
ββββββββββ₯ββββββββ¬ββββββββ¬ββββββββββββββ
β Number β First β Last βCountry β
ββββββββββ«ββββββββΌββββββββΌββββββββββββββ€
β1 βMark βTwain β USA β
ββββββββββ«ββββββββΌββββββββΌββββββββββββββ€
β2 βCharlesβDickensβGreat Britainβ
ββββββββββ«ββββββββΌββββββββΌββββββββββββββ€
β3 βJules βVerne β France β
ββββββββββ¨ββββββββ΄ββββββββ΄ββββββββββββββ
π«Ά SUPPORT π«Ά
π Websites
so there's a whole little ecosystem of sites with more info about this module, and they might genuinely help you out. and like, obviously also use your fave search engine to find even more resources β the internet is vast, bestie.
- MetaCPAN β a modern, open-source CPAN search engine, useful to view POD in HTML format.
<https://metacpan.org/release/Text-Table>
- RT: CPAN's Bug Tracker β the RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
<https://rt.cpan.org/Public/Dist/Display.html?Name=Text-Table>
- CPANTS β the CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.
<http://cpants.cpanauthors.org/dist/Text-Table>
- CPAN Testers β the CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.
<http://www.cpantesters.org/distro/T/Text-Table>
- CPAN Testers Matrix β the CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.
<http://matrix.cpantesters.org/?dist=Text-Table>
- CPAN Testers Dependencies β the CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.
<http://deps.cpantesters.org/?module=Text::Table>
π Bugs / Feature Requests
found a bug? want a feature? say something!! please report any bugs or feature requests by email to bug-text-table at rt.cpan.org, or through the web interface at <https://rt.cpan.org/Public/Bug/Report.html?Queue=Text-Table>. you'll get automatically notified of any progress on the request by the system β the system has your back β¨
π» Source Code
the code is open to the world, and available for you to hack on. please feel free to browse it and play with it, or whatever. if you want to contribute patches, please send me a diff or prod me to pull from your repository :)
<https://github.com/shlomif/Text-Table>
git clone git://github.com/shlomif/Text-Table.git
π AUTHOR π
Shlomi Fish <shlomif@cpan.org>
π BUGS π
please report any bugs or feature requests on the bugtracker website <https://github.com/shlomif/Text-Table/issues>
when submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. fr fr, a reproducer is everything β it's the difference between "hmm" and "oh we're fixing this today".
π COPYRIGHT AND LICENSE π
This software is Copyright (c) 2002 by Anno Siegel and others.
This is free software, licensed under:
The ISC License
π¦ SUPPORT π¦
okay so plot twist β the page literally says all of this again, and I'm not gonna rob you of a single character, so here it is, round two, same energy π
π Websites
The following websites have more information about this module, and may be of help to you. As always, in addition to those websites please use your favorite search engine to discover more resources.
- MetaCPAN β A modern, open-source CPAN search engine, useful to view POD in HTML format.
<https://metacpan.org/release/Text-Table>
- RT: CPAN's Bug Tracker β The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
<https://rt.cpan.org/Public/Dist/Display.html?Name=Text-Table>
- CPANTS β The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.
<http://cpants.cpanauthors.org/dist/Text-Table>
- CPAN Testers β The CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.
<http://www.cpantesters.org/distro/T/Text-Table>
- CPAN Testers Matrix β The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.
<http://matrix.cpantesters.org/?dist=Text-Table>
- CPAN Testers Dependencies β The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.
<http://deps.cpantesters.org/?module=Text::Table>
π Bugs / Feature Requests
Please report any bugs or feature requests by email to bug-text-table at rt.cpan.org, or through the web interface at <https://rt.cpan.org/Public/Bug/Report.html?Queue=Text-Table>. You will be automatically notified of any progress on the request by the system.
β Source Code
The code is open to the world, and available for you to hack on. Please feel free to browse it and play with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull from your repository :)
<https://github.com/shlomif/Text-Table>
git clone git://github.com/shlomif/Text-Table.git
π AUTHOR π
Shlomi Fish <shlomif@cpan.org>
π BUGS π
Please report any bugs or feature requests on the bugtracker website <https://github.com/shlomif/Text-Table/issues>
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.
π§ COPYRIGHT AND LICENSE π§
This software is Copyright (c) 2002 by Anno Siegel and others.
This is free software, licensed under:
The ISC License
and that's the whole page, bestie π you made it to the end β iconic behavior, genuinely. this little beauty ships as perl v5.42.0, dated 2022-10-13, filed under Text::Table(3pm). go forth and make immaculate tables π
β¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-Text-Table 1.135-bp160.1.1 Β· ISC
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms