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

Hi, I want to format a printf statement using a variable, i.e. if I had
printf "%-2s", $var1
how could I set the value for the format (the 2 in this case) using a variable, or is it not possible???

Thanks for any assistance

Replies are listed 'Best First'.
Re: Formating a printf statement using a variable
by mr.nick (Chaplain) on Jun 15, 2001 at 19:25 UTC
    Yes, it's quite possible:
    $a="%-2s"; printf $a,$b; $c="2s"; printf "%-$c",$b;

    mr.nick ...

Re: Formating a printf statement using a variable
by lemming (Priest) on Jun 15, 2001 at 19:26 UTC
    Try it out and see!
    use strict; use warnings; my $fmt = "%2.2f %02d %s\n" printf $fmt, 4.4, 3, "ta da!";
      Thanks to you all for the quick response, it now is working
Re: Formating a printf statement using a variable
by tadman (Prior) on Jun 15, 2001 at 20:31 UTC
    The "old fashioned" way of doing this, without string interpolation, is like so:      printf ("%-*s", 2, $var1); Where the asterisk indicates that the width of the field is supplied as an argument, which in this case is 2 but could easily be a variable or result of a calculation.

    Update: Albannach was kind enough to point out that this feature of the Perl printf was added in version 5.004. Historically, C compilers have supported this method since the beginning of time, since there is no built in "string interpolation" method.
Re: Formating a printf statement using a variable
by Marza (Vicar) on Jan 10, 2003 at 02:37 UTC

    I just love this place. I had a simliar issue and bam here is the answer on the search.

    A differnt version of the question involved displaying columnized data.

    If a word was larger then a certain size then I needed differnt columns and a print size. Using the offered method:

    use strict; use warnings; my $fmt = "%-$print_size" . "s"; printf("$fmt","$_");

    Thanks again and though it is late ++all

      Why not simply so? printf "%-${print_size}s", $_;

      Also note the lack of quotes around $_ - if you just refer to a variable by itself, don't interpolate it. There are cases where you need to do that, but you'll know them when you come across them. Most of the time it's just a wasted node in the optree and can even break code that would work fine without the quotes.

      HTH

      Makeshifts last the longest.

        Even better! Thank you! One less line and variable! I didn't know you could do that! ;-)