我想输出一个包含四个变量的表,所需格式的示例是:
A confusion matrix
H | P |
-----------------------
$var1 | $var2 | H
$var3 | $var4 | P
我遇到的问题是,根据变量中的位数,格式会发生变化,并且各行会发生偏移。我知道这完全是一个菜鸟问题,但我以前从未需要过多关注输出的格式,这只是我这次想要做对的小事情之一。任何帮助都会很棒,谢谢。
除了daxim的建议之外,还有Text::TabularDisplay。
您想要“格式”构造(某种程度上继承自 Fortran(!))
带有代码的真实示例 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 |
'--------+-----'
如果您不想安装其他 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 |
+-------------------------+-----+
这种语法非常古老且令人困惑。由你决定。
新模块 Text::Table::Boxed 基于 Text::Table 构建,自动提供边框和规则,包括对多行单元格的支持。
Text::Table支持各种对齐选项(它内部使用Text::Aligner),这些功能可以通过Text::Table
获得binmode STDOUT, ":utf8";
use Text::Table::Boxed;
my $tb = Text::Table::Boxed->new({
columns => [ {title => "Person",align => 'center'}, "Age", "Notes" ],
style => "boxrule",
});
$tb->load(
[ "Mother", 59, "Hi Mom!" ],
[ "Dad", 58, "Go Dodgers!" ],
[ "me", 32, "I like to type" ],
[ "Genghis Kahn", 804, "If I am able to achieve my 'Great Work',\n"
."I shall [always] share with you men the\n"
."sweet and the bitter. If I break this word,\n"
."may I be like the water of the River,\n"
."drunk up by others."
],
[ "Kushim", 5000, "A real OG" ],
);
print $tb;
产生:
┌──────────────┬──────┬─────────────────────────────────────────────┐
│ Person │ Age │ Notes │
╞══════════════╪══════╪═════════════════════════════════════════════╡
│ Mother │ 59 │ Hi Mom! │
├──────────────┼──────┼─────────────────────────────────────────────┤
│ Dad │ 58 │ Go Dodgers! │
├──────────────┼──────┼─────────────────────────────────────────────┤
│ me │ 32 │ I like to type │
├──────────────┼──────┼─────────────────────────────────────────────┤
│ Genghis Kahn │ 804 │ If I am able to achieve my 'Great Work', │
│ │ │ I shall [always] share with you men the │
│ │ │ sweet and the bitter. If I break this word, │
│ │ │ may I be like the water of the River, │
│ │ │ drunk up by others. │
├──────────────┼──────┼─────────────────────────────────────────────┤
│ Kushim │ 5000 │ A real OG │
└──────────────┴──────┴─────────────────────────────────────────────┘