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",开发者_如何学JAVA$_;
}
}
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.
Sounds like you should just use Data::Format::Pretty::Console
There are a number of modules for 'pretty-printing' text tables; my favourite is 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.
精彩评论