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

I use the sprintf function for table printing:

my $capion=sprintf "%-20s%30s%10s%10s%10s%10s%10s%10s%10s", 'Var1', "Var2", "Var3", 'Var4', 'Var5', "Var6", 'Var7', 'Var8',' +Var9';

I would also like to resize the table dynamically so that the spaces between collumns are not to large if this is not needed. Is it somehow possible to insert variables instead of numbers in the formating section of the sprintf function? Thank you for any help.

Replies are listed 'Best First'.
Re: Dynamical formating with sprintf?
by jettero (Monsignor) on Feb 14, 2008 at 18:33 UTC

    sprintf '%*s', length $x, $x

    Also, consider using Text::Table. It's worth it.

    -Paul

Re: Dynamical formating with sprintf?
by BrowserUk (Patriarch) on Feb 14, 2008 at 18:34 UTC

    Yes. Use * inplace of the number in the format string and use a variable before the item to be output. An example is probably clearer:

    [0] Perl> printf "[%*s]\n", $_, 'fred' for 4 .. 10;; [fred] [ fred] [ fred] [ fred] [ fred] [ fred] [ fred] ## Added: left justified [0] Perl> printf "[%-*s]\n", $_, 'fred' for 4 .. 10;; [fred] [fred ] [fred ] [fred ] [fred ] [fred ] [fred ]

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Dynamical formating with sprintf?
by jwkrahn (Abbot) on Feb 14, 2008 at 20:58 UTC

    Also if you have a lot of fields using the same width you can specify the width once and refer to it in the other fields:

    $ perl -le'print sprintf q(%*s%*1$s%*1$s%*1$s%*1$s), 10, qw(one two th +ree four five)' one two three four five
Re: Dynamical formating with sprintf?
by Fletch (Bishop) on Feb 14, 2008 at 18:49 UTC

    Perl6::Form might also be of interest.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Dynamical formating with sprintf?
by swampyankee (Parson) on Feb 14, 2008 at 23:35 UTC

    Being productively lazy, I'd use a module (kudos to all the posters who suggested that).

    Another technique is to build the string being used as sprintf's format on the fly. I occasionally do this, mostly as it's about the easiest way to produce "pretty" output to a plain text file.


    emc

    Information about American English usage here and here.

    Floating point issues? Read this before posting: "What Every Computer Scientist Should Know about Floating Point Arithmetic"