Mahesh
Mahesh

Reputation: 233

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.

Upvotes: 2

Views: 6575

Answers (3)

rjh
rjh

Reputation: 50274

There are a number of modules for 'pretty-printing' text tables; my favourite is Text::ASCIITable.

Upvotes: 4

Quentin
Quentin

Reputation: 943142

Sounds like you should just use Data::Format::Pretty::Console

Upvotes: 6

Nathan Fellman
Nathan Fellman

Reputation: 127428

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.

Upvotes: 0

Related Questions