开发者

How do I output a text table in Perl?

I want to output a table containing four variables, an example of the desired format is:

A confusion matrix

H        |    P     |
-----------------------
$var1    |   $var2  | H
$var3    |   $var4  | P
开发者_JS百科

The problem I am having is that depending on the number of digits in the variables, the format changes and the various lines are offset. I know this is a complete noobie question, but I have never had to pay too much attention to the format of output before, its just one of those little things I want to get right this time. Any help at all would be great, thanks.


Text::Table, Text::SimpleTable::AutoWidth


In addition to daxim's suggestions, there is also Text::TabularDisplay.


You want "format" construct (somewhat inherited from Fortran(!))

http://perldoc.perl.org/functions/format.html


A real example with code with Text::SimpleTable::AutoWidth:

use strict; use warnings;
use Text::SimpleTable::AutoWidth;

print Text::SimpleTable::AutoWidth
    ->new( max_width => 55, captions => [qw/ Name Age /] )
    ->row( 'Mother', 59 )
    ->row( 'Dad', 58 )
    ->row( 'me', 32 )
    ->draw();

.--------+-----.
| Name   | Age |
+--------+-----+
| Mother | 59  |
| Dad    | 58  |
| me     | 32  |
'--------+-----'

If you prefer to not install another CPAN module, using format:

#!/usr/bin/env perl

use strict; use warnings;

my ($name, $age, $salary);

format Emp =
@<@<<<<<<<<<@|||||||||||@<@<<@<<@< 
'|', $name, '|', $salary, '|', $age, '|'
.

$~ = 'Emp';

# header
print <<EOF;
+----------------+--------+-----+
| Employee name  | salary | age |
+----------------+--------+-----+
EOF

my @n = ("Ali", "Raza", "Jaffer");
my @a  = (20, 30, 40);
my @s = (2000, 2500, 4000);

my $i = 0;
foreach (@n) {
   $name = $_;
   $salary = $s[$i];
   $age = $a[$i];
   write;
}

# footer
print "+-------------------------+-----+\n";

+----------------+--------+-----+
| Employee name  | salary | age |
+----------------+--------+-----+
| Ali            |      20|  20 |
| Raza           |      20|  20 |
| Jaffer         |      20|  20 |
+-------------------------+-----+

This syntax is very old and confusing. Up to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜