On 9/17/07, VUNETdotUS <[EMAIL PROTECTED]> wrote:
> I print some output in PERL. It is data in 3 columns. I use \t to add
> a tab space to make a column.
> However, \t may not produce the desired result. If the value is short
> in length, next column is not aligned correctly in the row. Something
> like this:
>
> 123     12345     123456
> 123     12345     123456
> 1     1234     123456
> 123     12345     123456
>
> How can I make a nicely formatted output?
snip

Welcome to a classic problem.  There are several solutions, but they
all have their drawbacks.  The best solution is to use a markup
language like html and create a table, but this is not really an
option for command line usage, the next best thing is to know what the
maximum size for each column and to use a printf instead of print,
then there is Perl6::Form, and a bunch of other modules that can help
format data.  In general, you can get away with this

#!/usr/bin/perl

use strict;
use warnings;

my @data = (
    [123, 12345, 123456],
    [1, 1234, 123456],
    [123, 12345, 123456],
);
for my $row (@data) {
    printf "%3.3s %5.5s %6.6s\n", @$row
}

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to