[ACCEPTED]-How do I output a text table in Perl?-formatting

Accepted answer
Score: 13
Score: 6

In addition to daxim's suggestions, there 1 is also Text::TabularDisplay.

Score: 4

You want "format" construct (somewhat 1 inherited from Fortran(!))

http://perldoc.perl.org/functions/format.html

Score: 0

A real example with code with Text::SimpleTable::AutoWidth:

use strict; use 3 warnings;

use Text::SimpleTable::AutoWidth;

print Text::SimpleTable::AutoWidth
    ->new( max_width => 55, captions => [qw/ Name Age /] )
    ->row( 'Mother', 59 )
    ->row( 'Dad', 58 )
    ->row( 'me', 32 )
    ->draw();

.--------+-----.
| Name   | Age |
+--------+-----+
| Mother | 59  |
| Dad    | 58  |
| me     | 32  |
'--------+-----'

If you prefer to not install another 2 CPAN module, using format:

#!/usr/bin/env perl

use strict; use warnings;

my ($name, $age, $salary);

format Emp =
@<@<<<<<<<<<@|||||||||||@<@<<@<<@< 
'|', $name, '|', $salary, '|', $age, '|'
.

$~ = 'Emp';

# header
print <<EOF;
+----------------+--------+-----+
| Employee name  | salary | age |
+----------------+--------+-----+
EOF

my @n = ("Ali", "Raza", "Jaffer");
my @a  = (20, 30, 40);
my @s = (2000, 2500, 4000);

my $i = 0;
foreach (@n) {
   $name = $_;
   $salary = $s[$i];
   $age = $a[$i];
   write;
}

# footer
print "+-------------------------+-----+\n";

+----------------+--------+-----+
| Employee name  | salary | age |
+----------------+--------+-----+
| Ali            |      20|  20 |
| Raza           |      20|  20 |
| Jaffer         |      20|  20 |
+-------------------------+-----+

This syntax is very 1 old and confusing. Up to you.

More Related questions