我正在使用CPAN Text::Table模块。我的脚本中有一个表,有些值是多行字符串。我也使用规则打印此表。
我的代码如下:
vectorOfMyClass.sortBy(_.field)
vectorOfMyClass.sortWith(_.field < _.field)
然而,当我运行时,我得到以下内容:
#!/usr/bin/perl5.14.1
use FindBin;
use lib "$FindBin::Bin/mylib/Text-Aligner-0.12/lib/";
use lib "$FindBin::Bin/mylib/Text-Table-1.130/lib/";
use Text::Table;
my $tb = Text::Table->new(\'| ', "", \' | ', "Field ", \'| ', "Length ", \'| ', "Comment ", \' |');
my @AoA = (
[ 1, "Foo", "20", "Foo" ],
[ 2, "Bar", "35", "Bar\nBar" ],
[ 3, "Tze", "10", "Tze\nTze" ],
);
$tb->load(@AoA);
my $rule = $tb->rule(qw/- /);
my @arr = $tb->body;
print $rule, $tb->title, $rule;
for (@arr) {
print $_ . $rule;
}
在多行字符串的情况下,有没有办法不打印单独的行?
我想按如下方式显示我的表格:
|---|-------|--------|----------|
| | Field | Length | Comment |
|---|-------|--------|----------|
| 1 | Foo | 20 | Foo |
|---|-------|--------|----------|
| 2 | Bar | 35 | Bar |
|---|-------|--------|----------|
| | | | Bar |
|---|-------|--------|----------|
| 3 | Tze | 10 | Tze |
|---|-------|--------|----------|
| | | | Tze |
|---|-------|--------|----------|
答案 0 :(得分:4)
Text::Table
代码会在数据的每一行上调用split( /\n/ )
,并将结果放入自己的行中。您可以通过计算哪些行实际对应于多行数据并仅在适当的边界打印规则来解决此问题:
use strict;
use warnings;
use List::Util qw(max);
use Text::Table;
my $sep = \'|';
my @col_spec = ($sep, '', $sep, 'Field', $sep, 'Length', $sep, 'Comment', $sep);
my $tb = Text::Table->new(@col_spec);
my @data = (
[ 1, "Foo", "20", "Foo" ],
[ 2, "Bar\nBaz\nQux", "35", "Bar\nBar" ],
[ 3, "Tze", "10", "Tze\nTze" ]
);
# Track which rows should be preceded by rules. A key of 'n' indicates that a
# rule should be printed before the nth row (zero-indexed).
my %indexes = (
0 => 1, # Before header row
1 => 1 # After header row
);
# Calculate body rows for which rules should be printed
my $count = 1;
foreach my $row (@data) {
# Greatest number of newlines in row
my $newlines = max map { tr/\n// } @$row;
# One newline corresponds to two rows
$count += $newlines + 1;
$indexes{$count} = 1;
}
$tb->load(@data);
my $rule = $tb->rule('-', '+');
foreach my $i (0 .. $tb->height) {
print $rule if exists $indexes{$i};
print $tb->table($i);
}
+-+-----+------+-------+
| |Field|Length|Comment|
+-+-----+------+-------+
|1|Foo |20 |Foo |
+-+-----+------+-------+
|2|Bar |35 |Bar |
| |Baz | |Bar |
| |Qux | | |
+-+-----+------+-------+
|3|Tze |10 |Tze |
| | | |Tze |
+-+-----+------+-------+