Text::Table主要用于列宽的计数,有个不完善的地方就是数组中最长一行的字符数得自己估计,主要是懒得写了,而且也不是重点,所以就省了。
一、示例代码1:
- #use Acme::PerlTidy;
- use Text::Table;
- my @a = (
- [ '18m 12s', 't/acceptance.t' ],
- [ '4m 13s', 't/aggregate.t' ],
- [ '4m 14s', 't/aggregate.t', 'host' ],
- [ '4m 15s', 't/aggregate.t', 'host', 'name' ],
- [ '4m 16s', 't/aggregate.ta', 'host', 'name', 'name' ]
- );
- #my $arr = $arr_re;二维数组的引用
- #my $width = '50';自已估计数组中最长一行的字符数
- #my $label_p = '+';端点连接符
- #my $label_r = '-';行连接符
- #my $label_c = '|';列连接符
- print "例一:以-做为端点\n";
- make_table( \@a, '50', '-', '-', '|' );
- print "例二:以+做为端点\n";
- make_table( \@a, '50', '+', '-', '|' );
- sub make_table {
- my ( $arr, $width, $label_p, $label_r, $label_c ) = @_;
- my @form_L;
- for my $m ( 0 .. @$arr - 1 ) {
- my $tb = Text::Table->new();
- $tb->load( $arr->[$m] );
- my $cols = $tb->n_cols;
- my @form = '';
- my @str = '';
- my $sum;
- for my $n ( 0 .. $cols - 1 ) {
- my $col_with = $tb->colrange($n);
- my $tb_with = $tb->width;
- my $length = int( $width * $col_with / $tb_with + 0.5 );
- $sum += $length;
- if ( $n == $cols - 1 ) {
- $length = $length + $width - $sum - $n - 2;
- }
- push( @form, "$label_r" x "$length" );
- my $sub = $tb->select($n);
- $sub =~ s/\n//g;
- my $format = '%-' . $length . 's';
- push( @str, sprintf( $format, $sub ) );
- }
- print join( $label_p, @form ), "$label_p\n";
- print join( $label_c, @str ), "$label_c\n";
- @form_L = @form;
- }
- print join( $label_p, @form_L ), "$label_p\n";
- }
输出结果如下:
二、示例代码2:
- #use Acme::PerlTidy;
- use Text::Table;
- my $title = [ Time, Test, 'host', 'namee' ];
- my $rows = [
- [ '18m 12s', 't/acceptance.t' ],
- [ '4m 13s', 't/aggregate.t' ],
- [ '4m 14s', 't/aggregate.t', 'host' ],
- [ '4m 15s', 't/aggregate.t', 'host', 'name' ],
- [ '4m 16s', 't/aggregate.ta', 'host', 'namee', 'nameeeeeee' ]
- ];
- print make_table( $title, $rows, );
- sub make_table {
- my ( $headers, $rows ) = @_;
- my @rule = qw(- +);
- my @headers = \'|';
- push @headers => map { $_ => \'|' } @$headers;
- my $table = Text::Table->new(@headers);
- $table->load(@$rows);
- return $table->rule(@rule),
- $table->title,
- $table->rule(@rule),
- map( { $table->body($_) } 0 .. @$rows ),
- $table->rule(@rule);
- }
输出结果如下:
阅读(2468) | 评论(0) | 转发(0) |