简体   繁体   中英

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

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.

除了 daxim 的建议,还有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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM