Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I've problem with aligning tabbed strings. My code looks something like this:

my $output = qq~Username\tLevel\tCreated\n~; foreach my $row (@rows) { $output .= qq~$row->[0]\t$row->[1]\t$row->[2]\n~; }

And I get something like this:

Username Level Created johnny 2 12-09-2008 rob 2 25-10-2008

Is there a way to align the value of each row correctly under each heading?

Thanks in advance :)

Replies are listed 'Best First'.
Re: How to align tabbed strings?
by WizardOfUz (Friar) on Jan 02, 2010 at 14:54 UTC

      Thank you so much, WizardOfUz!

      I chose Text::Table, it works beautifully :)

Re: How to align tabbed strings?
by FunkyMonk (Bishop) on Jan 02, 2010 at 16:05 UTC
    As WizardOfUz has said, Text::Table will do as you want (and a whole lot more). Perhaps a simpler solution using printf (the formatting codes are described in sprintf) will do:
    my @rows = ( [qw/johnny 2 12-09-2008/], [qw/rob 2 25-10-2008/], ); my $format = "%-8s %-5s %-8s\n"; printf $format, qw/Username Level Created/; printf $format, @$_ for @rows; __END__ Username Level Created johnny 2 12-09-2008 rob 2 25-10-2008


    Unless I state otherwise, all my code runs with strict and warnings

      Wonderful, thank you so much!

      Instead of printing, is it possible to save the formatted string into a variable (scalar), so that you can send it off (for instance) as a message in email (via sendmail)?

        That's what sprintf does!

        my $format = "%-8s %-5s %-8s\n"; my $output = sprintf $format, qw/Username Level Created/; $output .= sprintf $format, @$_ for @rows;

Re: How to align tabbed strings?
by johngg (Canon) on Jan 02, 2010 at 16:24 UTC

    It is good that WizardOfUz's suggestion of Text::Table is working well for you. It is also worth being familiar with printf for application to simple problems.

    $ perl -e ' > $format = qq{%-10s%-7s%-12s\n}; > @headings = qw{ Username Level Created }; > printf $format, @headings; > @rows = ( > [ qw{ johnny 2 12-09-2008 } ], > [ qw{ rob 2 25-10-2008 } ], > ); > printf $format, @$_ for @rows;' Username Level Created johnny 2 12-09-2008 rob 2 25-10-2008 $

    I hope this is useful.

    Cheers,

    JohnGG

    Update: Looks like FunkyMonk beat me to it, must learn to type faster :-/