[英]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(!))你想要“格式”构造(有点继承自 Fortran(!))
http://perldoc.perl.org/functions/format.html http://perldoc.perl.org/functions/format.html
A real example with code with Text::SimpleTable::AutoWidth :一个带有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 :如果您不想安装另一个 CPAN 模块,请使用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.由你决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.