简体   繁体   English

perl打印表输出

[英]perl printing table output

I am trying to print output in tabular format. 我试图以表格格式打印输出。

my Script: 我的剧本:

use strict;
my @heading=("FN","SN","BP","SUBBN","LgcBT");
my @values=("1","0","Front","Mother Board","MIU");
print "\n\n";
&HEADING;
print "\n";
&VALUES;
print "\n\n";

sub HEADING {
    foreach (@heading) {
        my $lgth1=length($_);
        printf "%3s","| ";
        printf "%${lgth1}s",$_;
    }
}

sub VALUES {
    foreach (@values) {
        my $lgth2=length($_);
        printf "%3s","| ";
        printf "%${lgth2}s",$_;
    }
}

Output: 输出:

 | FN | SN | BP | **SUBBN** | LgcBT

 | 1 | 0 | Front | **Mother Board** | MIU

I need to print output in a way that if value is longer than heading then it automatically adjusts length of heading to that of value. 我需要以一种方式打印输出,如果值比标题长,那么它会自动将标题长度调整为值。

听起来你应该只使用Data :: Format :: Pretty :: Console

There are a number of modules for 'pretty-printing' text tables; “漂亮打印”文本表有许多模块; my favourite is Text::ASCIITable . 我最喜欢的是Text :: ASCIITable

The way to do it is to generate a length array in advance: 这样做的方法是提前生成一个长度数组:

my @lengths;
for (0..$#lengths) {
    $lengths[$_] = (length($headers[$_]) > length($values[$_])) ? length($headers[$_]) : length($values[$_])
}

Of course, there are better ways to generate @lengths that are more Perl-ish, but IMHO this example is the easiest to read. 当然,有更好的方法来生成更多Perl-ish的@lengths ,但恕我直言这个例子是最容易阅读的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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