LaTeX::Table(3pm)
π LaTeX::Table π
(that's LaTeX::Table(3pm) bestie β straight outta the User Contributed Perl Documentation section, and yes it's a whole vibe)
okay so listen. you want LaTeX tables. you want them pretty. you do not want to hand-write \multicolumn forty-seven times like it's the dark ages. good news: this module is about to be your new best friend. let's go π«Ά
β¨ NAME β¨
LaTeX::Table β a Perl extension for the automatic generation of LaTeX tables. no cap, that's the whole job. π
β¨ VERSION β¨
This document describes LaTeX::Table version 1.0.6.
πΈ SYNOPSIS πΈ
okay so here's the whole thing in action. you set up a header, you set up some data, you vibe:
use LaTeX::Table;
use Number::Format qw(:subs); # use mighty CPAN to format values
my $header = [
[ 'Item:2c', '' ],
[ '\cmidrule(r){1-2}' ],
[ 'Animal', 'Description', 'Price' ],
];
my $data = [
[ 'Gnat', 'per gram', '13.65' ],
[ '', 'each', '0.0173' ],
[ 'Gnu', 'stuffed', '92.59' ],
[ 'Emu', 'stuffed', '33.33' ],
[ 'Armadillo', 'frozen', '8.99' ],
];
my $table = LaTeX::Table->new(
{
filename => 'prices.tex',
maincaption => 'Price List',
caption => 'Try our special offer today!',
label => 'table:prices',
position => 'tbp',
header => $header,
data => $data,
}
);
# write LaTeX code in prices.tex
$table->generate();
# callback functions help you to format values easily (as
# a great alternative to LaTeX packages like rccol)
#
# Here, the first colum and the header is printed in upper
# case and the third colum is formatted with format_price()
$table->set_callback(sub {
my ($row, $col, $value, $is_header ) = @_;
if ($col == 0 || $is_header) {
$value = uc $value;
}
elsif ($col == 2 && !$is_header) {
$value = format_price($value, 2, '');
}
return $value;
});
print $table->generate_string();
then over in your LaTeX document you do this π :
\documentclass{article}
% for multi-page tables (xtab or longtable)
\usepackage{xtab}
%\usepackage{longtable}
% for publication quality tables (Meyrin theme, the default)
\usepackage{booktabs}
% for the NYC theme
\usepackage{array}
\usepackage{colortbl}
\usepackage{xcolor}
\begin{document}
\input{prices}
\end{document}
π¦ DESCRIPTION π¦
so, LaTeX makes professional typesetting easy β iconic, love that for it. but that is not entirely true for tables, and the standard LaTeX table macros have a rather limited functionality. lowkey tragic.
This module supports many CTAN packages and hides all the complexity of using them behind an easy and intuitive API. it's giving "you don't need to know the lore, bestie, i got you." β¨
π FEATURES π
look at everything she can do:
- multi-page tables via the
xtabor thelongtablepackage ππ - for publication quality tables, she uses the
booktabspackage β¨ - also supports the
tabularxandtabularypackages for nicer fixed-width tables π - plus the
colortblpackage for colored tables optimized for presentations π¨ (main character energy, honestly) - the powerful new
ctablepackage is supported and especially recommended when footnotes are needed π«Ά LaTeX::Tableships with some predefined, good looking THEMES π- the program ltpretty makes it possible to use this module from within a text editor π§
π INTERFACE π
π my $table = LaTeX::Table->new($arg_ref)
Constructs a LaTeX::Table object. The parameter is an hash reference with options β see below, we get into all of them. no skipping, bestie, i know you want to. π
π $table->generate()
Generates the LaTeX table code. The generated LaTeX table can be included in a LaTeX document with the \input command:
% include prices.tex, generated by LaTeX::Table
\input{prices}
π $table->generate_string()
Same as generate() but instead of creating a LaTeX file, this returns the LaTeX code as a string. π§΅
my $latexcode = $table->generate_string();
π $table->get_available_themes()
Returns an hash reference to all available themes. See THEMES for details.
for my $theme ( keys %{ $table->get_available_themes } ) {
...
}
π $table->search_path( add => "MyThemes" );
LaTeX::Table will search under the LaTeX::Table::Themes:: namespace for themes. You can add here an additional search path. Inherited from Module::Pluggable. π
π OPTIONS π
okay so here's the deal: options can be defined in the constructor hash reference or with the setter set_optionname. Additionally, getters of the form get_optionname are created. so it's setters and getters, because of course she's generous like that. π
πΈ BASIC OPTIONS πΈ
filenameβ the name of the LaTeX output file. Default is'latextable.tex'. ποΈtypeβ can be'std'(default) for standard LaTeX tables,'ctable'for tables using thectablepackage, or'xtab'and'longtable'for multi-page tables (requires thextabandlongtableLaTeX packages, respectively).headerβ the header. It is a reference to an array (the rows) of array references (the columns). so, arrays of arrays, nesting doll situation, you know the drill πͺ
$table->set_header([ [ 'Animal', 'Price' ] ]);
will produce following header:
+--------+-------+
| Animal | Price |
+--------+-------+
Here an example for a multirow header:
$table->set_header([ [ 'Animal', 'Price' ], ['', '(roughly)' ] ]);
This code will produce this header:
+--------+-----------+
| Animal | Price |
| | (roughly) |
+--------+-----------+
Single column rows that start with a backslash are treated as LaTeX commands and are not further formatted. So,
my $header = [
[ 'Item:2c', '' ],
['\cmidrule{1-2}'],
[ 'Animal', 'Description', 'Price' ]
];
will produce following LaTeX code in the Zurich theme:
\multicolumn{2}{c}{\textbf{Item}} & \\
\cmidrule{1-2}
\textbf{Animal} & \multicolumn{1}{c}{\textbf{Description}} & \multicolumn{1}{c}{\textbf{Price}}\\
Note that there is no \multicolumn, \textbf or \\ added to the second row. she leaves it exactly as you wrote it. respect. π
dataβ the data. Once again a reference to an array (rows) of array references (columns).
$table->set_data([ [ 'Gnu', '92.59' ], [ 'Emu', '33.33' ] ]);
And you will get a table like this:
+-------+---------+
| Gnu | 92.59 |
| Emu | 33.33 |
+-------+---------+
An empty column array will produce a horizontal rule (line):
$table->set_data([ [ 'Gnu', '92.59' ], [], [ 'Emu', '33.33' ] ]);
Now you will get such a table:
+-------+---------+
| Gnu | 92.59 |
+-------+---------+
| Emu | 33.33 |
+-------+---------+
This works also in header. β¨
Single column rows starting with a backslash are again printed without any formatting. So,
$table->set_data([ [ 'Gnu', '92.59' ], ['\hline'], [ 'Emu', '33.33' ] ]);
is equivalent to the example above (except that there always the correct rule command is used, i.e. \midrule vs. \hline).
custom_templateβ the table types listed above use the Template toolkit internally. These type templates are very flexible and powerful, but you can also provide a custom template:
# Returns the header and data formatted in LaTeX code. Nothing else.
$table->set_custom_template('[% HEADER_CODE %][% DATA_CODE %]');
See LaTeX::Table::Types::TypeI. π
π FLOATING TABLES π
environmentβ ifget_environment()returns a true value, then a floating environment will be generated. For std tables, the default environment is'table'. A true value different from'1'will be used as environment name. Default is 1 (use a'table'environment).
The non-floating xtab and longtable environments are mandatory (get_environment() must return a true value here) and support all options in this section except for position.
The ctable type automatically adds an environment when any of the following options are set.
captionβ the caption of the table. Only generated ifget_caption()returns a true value. Default is 0. Requiresenvironment. πcaption_topβ ifget_caption_top()returns a true value, then the caption is placed above the table. To use the standard caption command (\captionin std and longtable,\topcaptionin xtab), use
...
caption_top => 1,
...
You can specify an alternative command here:
...
caption_top => 'topcaption', # would require the topcapt package
Or even multiple commands:
caption_top =>
'\setlength{\abovecaptionskip}{0pt}\setlength{\belowcaptionskip}{10pt}\caption',
...
Default 0 (caption below the table) because the spacing in the standard LaTeX macros is optimized for bottom captions. At least for multi-page tables, however, top captions are highly recommended. You can use the caption LaTeX package to fix the spacing:
\usepackage[tableposition=top]{caption}
ok bestie real talk: the default is bottom captions, that's just how the standard macros are tuned. but the second you're doing multi-page tables, put that caption on top, you'll thank yourself. π
maincaptionβ ifget_maincaption()returns a true value, then this value will be displayed in the table listing (\listoftables) and before thecaption. For example,
maincaption => 'Price List',
caption => 'Try our special offer today!',
will generate
\caption[Price List]{Price List. Try our special offer today!}
Themes can set the font family of the maincaption.
Default 0. Requires environment.
shortcaptionβ same asmaincaption, but does not appear in the caption, only in the table listing. Default 0. Requiresenvironment.continuedβ if true, then the table counter will be decremented by one and thecontinuedmsgis appended to the caption. Useful for splitting tables. Default 0. βοΈ
$table->set_continued(1);
continuedmsgβ ifget_continued()returns a true value, then this text is appended to the caption. Default'(continued)'.center,right,leftβ defines how the table is aligned in the available textwidth. Default is centered. Requiresenvironment. Only one of these options may return a true value. pick a lane, bestie, you can't be all three π
# don't generate any aligning code
$table->set_center(0);
...
# restore default
$table->clear_center();
labelβ the label of the table. Only generated ifget_label()returns a true value. Default is 0. Requiresenvironment. π·οΈ
$table->set_label('tbl:prices');
positionβ the position of the environment, e.g.'tbp'. Only generated ifget_position()returns a true value. Default 0. Requiresenvironmentand tables oftypestd or ctable. πsidewaysβ rotates the whole environment 90 degrees, like the table's doing a lil spin π« Default is0. For tables oftypestdandctablethis needs therotatingLaTeX package; forxtaborlongtabletables you need thelscapepackage instead.
$table->set_sideways(1);
starβ uses the starred versions of the environments, which throw the float over two columns when thetwocolumnoption or the\twocolumncommand is active. Default0.
$table->set_star(1);
fontfamilyβ valid values are'rm'(Roman, serif),'sf'(Sans-serif),'tt'(Monospace or typewriter) and0. Default is0, meaning it does not define a font family. Requiresenvironment.fontsizeβ valid values are'tiny','scriptsize','footnotesize','small','normal','large','Large','LARGE','huge','Huge'and0. Default is0(does not define a font size). Requiresenvironment.
π TABULAR ENVIRONMENT π
custom_tabular_environmentβ ifget_custom_tabular_environment()returns a true value, then the environment you specified here gets used instead of the standard ones:'tabular'(std),'longtable'(longtable) or'xtabular'(xtab). For xtab tables you can also drop'mpxtabular'in here if you need footnotes β go read the docs of thextabpackage for that one. π
Also peep the docs for width below for the cases when a width is specified.
coldefβ the table column definition, e.g.'lrcr', which would give you:
\begin{tabular}{lrcr}
..
If you leave it unset, LaTeX::Table tries to guess a good definition for you (bestie's got you). Columns containing only numbers are right-justified, everything else left-justified. Columns with cells longer than 30 characters become p (paragraph) columns of size '5cm' (X columns when the tabularx package is selected, L when tabulary is). These rules can be changed with set_coldef_strategy(). Default is 0 (guess good definition). The left-hand column, the stub, is normally excluded here and is always left aligned. See LaTeX::Table::Themes::ThemeI.
coldef_strategyβ controls the behavior of thecoldefcalculation whenget_coldef()does not return a true value. It's a reference to a hash that contains regular expressions defining the types of the columns. For example, the standard types NUMBER and LONG are defined as:
{
NUMBER =>
qr{\A\s*([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?\s*\z}xms,
NUMBER_MUST_MATCH_ALL => 1,
NUMBER_COL => 'r',
LONG => qr{\A\s*(?=\w+\s+\w+).{29,}?\S}xms,
LONG_MUST_MATCH_ALL => 0,
LONG_COL => 'p{5cm}',
LONG_COL_X => 'X',
LONG_COL_Y => 'L',
};
TYPE => $regexβ new types are defined with the regular expression $regex. All cells that match this regular expression have type TYPE. A cell can have multiple types. The name of a type is not allowed to contain underscores (_).TYPE_MUST_MATCH_ALLβ this defines whether a column has type TYPE when all cells are of type TYPE or when at least one is. Default is1($regex must match all).
Heads up bestie: columns can have only one type. Types are applied alphabetically, so for example a LONG NUMBER column has as final type NUMBER. π
TYPE_COLβ thecoldefattribute for TYPE columns. Required (no default value).TYPE_COL_X,TYPE_COL_Yβ same asTYPE_COLbut fortabularxortabularytables. If undefined, the attribute defined inTYPE_COLis used.DEFAULT_COL,DEFAULT_COL_X,DEFAULT_COL_Yβ thecoldefattribute for columns that do not match any specified type. Default'l'(left-justified).MISSING_VALUE => $regexβ column values that match the specified regular expression are omitted in thecoldefcalculation. Default isqr{\A \s* \z}xms.
Examples, because we love a lil demo:
# change standard types
$table->set_coldef_strategy({
NUMBER => qr{\A \s* \d+ \s* \z}xms, # integers only
LONG_COL => '>{\raggedright\arraybackslash}p{7cm}', # non-justified
});
# add new types (here: columns that contain only URLs)
$table->set_coldef_strategy({
URL => qr{\A \s* http }xms,
URL_COL => '>{\ttfamily}l',
});
widthβ ifget_width()returns a true value, thenLaTeX::Tablewill use the starred version of the environment (e.g.tabular*orxtabular*) and will add the specified width as second parameter. It will also add@{\extracolsep{\fill}}to the table column definition:
# use 75% of textwidth
$table->set_width('0.75\textwidth');
This will produce following LaTeX code:
\begin{tabular*}{0.75\textwidth}{l@{\extracolsep{\fill} ... }
For tables of type std, it is also possible to use the tabularx and tabulary LaTeX packages (see width_environment below). The tables of type ctable automatically use the tabularx package. See also width_environment for how to use this feature with longtable.
width_environmentβ ifget_width()(see above) returns a true value and table is oftypestd, then this option provides the possibility to add a custom tabular environment that supports a table width:
\begin{environment}{width}{def}
To use for example the one provided by the tabularx LaTeX package, write:
# use the tabularx package (for a std table)
$table->set_width('300pt');
$table->set_width_environment('tabularx');
Note this will not add @{\extracolsep{\fill}} and that this overwrites a custom_tabular_environment.
It is possible to use tabularx together with tables of type longtable. In this case, you have to generate a file and then load the table with the LTXtable command (ltxtable package):
$table = LaTeX::Table->new(
{ filename => 'mylongtable.tex'
type => 'longtable',
...
width_environment => 'tabularx',
}
);
Then in LaTeX:
\LTXtable{0.8\textwidth}{mylongtable}
Note that we have to do the specification of the width in LaTeX.
Default is 0 (see width).
maxwidthβ only supported by tables of type ctable.eorβ string specifying the end of a row. Default is'\\'.
$table->set_eor("\\\\[1em]");
Callback functions (see below) can be used to manually set the eor after the last column. This is useful when some rows require different eor strings. β¨
callbackβ ifget_callback()returns a true value and the return value is a code reference, then this callback function will be called for every column inheaderanddata. The return value of this function is then printed instead of the column value.
The passed arguments are $row, $col (both starting with 0), $value and $is_header.
use LaTeX::Encode;
use Number::Format qw(:subs);
...
# rotate header (not the first column),
# use LaTeX::Encode to encode LaTeX special characters,
# format the third column with Format::Number (only the data)
my $table = LaTeX::Table->new(
{ header => $header,
data => $data,
callback => sub {
my ( $row, $col, $value, $is_header ) = @_;
if ( $col != 0 && $is_header ) {
$value = '\begin{sideways}' . $value . '\end{sideways}';
}
elsif ( $col == 2 && !$is_header ) {
$value = format_price($value, 2, '');
}
else {
$value = latex_encode($value);
}
return $value;
},
}
);
foottableβ only supported by tables of typectable. The footnote\tnotecommands. See the documentation of thectableLaTeX package.
$table->set_foottable('\tnote{footnotes are placed under the table}');
resizeboxβ ifget_resizebox()returns a true value, then the resizebox command is used to resize the table. Takes as argument a reference to an array. The first element is the desired width. If a second element is not given, then the height is set to a value so that the aspect ratio is still the same. Requires thegraphicxLaTeX package. Default0.
$table->set_resizebox([ '0.6\textwidth' ]);
$table->set_resizebox([ '300pt', '200pt' ]);
π MULTI-PAGE TABLES π
tableheadmsgβ whenget_caption_top()andget_tableheadmsg()both return true values, then additional captions are printed on the continued pages. Default caption text is'Continued from previous page'.tabletailmsgβ message at the end of a multi-page table. Default is'Continued on next page'. When usingcaption_top, this is in most cases unnecessary and it is recommended to omit the tabletail (see below).tabletailβ custom table tail. Default is multicolumn with the tabletailmsg (see above) right-justified.
# don't add any tabletail code:
$table->set_tabletail(q{});
tablelasttailβ same astabletail, but defines only the bottom of the last page ('lastfoot'in thelongtablepackage). Default''.xentrystretchβ option for xtab. Play with this option if the number of rows per page is not optimal. Requires a number as parameter. Default is0(does not use this option).
$table->set_xentrystretch(-0.1);
π THEMES π
themeβ the name of the theme. Default is Meyrin (requiresbooktabsLaTeX package).
See LaTeX::Table::Themes::ThemeI how to define custom themes.
The themes are defined in LaTeX::Table::Themes::Beamer, LaTeX::Table::Themes::Booktabs, LaTeX::Table::Themes::Classic, LaTeX::Table::Themes::Modern.
$table->set_theme('Zurich');
predef_themesβ all predefined themes. Getter only. πcustom_themesβ all custom themes. See LaTeX::Table::Themes::ThemeI.columns_like_headerβ takes as argument a reference to an array with column ids (again, starting with 0). These columns are formatted like header columns.
# a "transposed" table ...
my $table = LaTeX::Table->new(
{ data => $data,
columns_like_header => [ 0 ], }
);
π MULTICOLUMNS π
Okay bestie, so in LaTeX a multicolumn is this whole thing: \multicolumn{$cols}{$alignment}{$text}. And this module is like "nah, too much typing" and gives you a lil shortcut instead: "$text:$cols$alignment". β¨
So for example, Item:2c is literally equivalent to \multicolumn{2}{c}{Item}. Same thing. Periodt. π
Heads up though: vertical rules (|) get automatically added here according to the rules settings in the theme. Go peek atLaTeX::Table::Themes::ThemeIfor that.
And LaTeX::Table also uses this same shortcut to figure out the column ids. So in this example:
my $data = [ [' \multicolumn{2}{c}{A}', 'B' ], [ 'C:2c', 'D' ] ];
'B' would have a column id of 1 and 'D' would have 2 β because 'A' and 'C' are both id 0. π This is lowkey important, for callback functions and for the coldef calculation. See "TABULAR ENVIRONMENT".
π¦ EXAMPLES π¦
Go look at examples/examples.pdf in this distribution β it's a short tutorial covering the main features of this module. Chef's kiss, fr fr. π
Also check out the example application csv2pdf for an example of that super common task: converting a CSV (or Excel) file to LaTeX or even PDF. Iconic.
π DIAGNOSTICS π
If you get a LaTeX error message, please check whether you've included all the required packages. The packages we use are array, booktabs, colortbl, ctable, graphicx, longtable, lscape, rotating, tabularx, tabulary, xcolor and xtab. That's the whole roster, no skipping. π
LaTeX::Table may throw one of these errors:
"IO error: Can't ..."β In methodgenerate(), it was not possible to write the LaTeX code tofilename."Invalid usage of option ..."β In methodgenerate()orgenerate_string(). See the examples in this document and inexamples/examples.pdffor the correct usage of this option."Attribute (option) ... "β In methodnew()orset_option(). You passed a wrong type to the option. See this document orexamples/examples.pdffor the correct usage of this option.
π§ CONFIGURATION AND ENVIRONMENT π§
LaTeX::Table requires no configuration files or environment variables. Zero setup, zero drama. β¨
π DEPENDENCIES π
Carp, Module::Pluggable, Moose, English, Scalar::Util, Template
π BUGS AND LIMITATIONS π
The width option causes problems with themes using the colortbl package. You may have to specify here the overhang arguments of the \columcolor commands manually. Patches are of course welcome. π«Ά
Problems with the width option are also known for tables of type longtable. You should use the tabularx package as described in the width_environment documentation.
Please report any bugs or feature requests to bug-latex-table@rt.cpan.org, or through the web interface at http://rt.cpan.org.
β SEE ALSO β
Data::Table, LaTeX::Encode
π CREDITS π
- ANDREWF, ANSGAR and REHSACK for some great patches and suggestions.
- David Carlisle for the
colortbl,longtable,ltxtable,tabularxandtabularyLaTeX packages. - Wybo Dekker for the
ctableLaTeX package. - Simon Fear for the
booktabsLaTeX package. TheSYNOPSIStable is the example in his documentation. - Lapo Filippo Mori for the excellent tutorial Tables in LaTeX2e: Packages and Methods.
- Peter Wilson for the
xtabLaTeX package.
π LICENSE AND COPYRIGHT π
Copyright (c) 2006-2010 "<limaone@cpan.org>"
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.
πΈ DISCLAIMER OF WARRANTY πΈ
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENSE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
and that's a wrap, bestie!! π¬π this whole page is from the LaTeX::Table(3pm) manual, generated for perl v5.34.0, dated 2022-06-15. go forth and make pretty tables, you absolute icon πβ¨
π¦ where this page comes from
- debian bookworm: liblatex-table-perl 1.0.6-4 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: liblatex-table-perl 1.0.6-4 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: liblatex-table-perl 1.0.6-4 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms