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

hi there,

i am trying to get the printf function to print a variable. the issue is complex (for me) as the variable i am trying to print(f) contains strings and integers. i would like to print in a nice format. is this possible.... ? see my example code:

my $pi = 3.14159; printf "%11s %3d %5.1f\n", "Hello there", 123, $pi; # this works fine +! $newarray="%11s %3d %5.1f\nHello there"; $newarray.=" 123 $pi"; printf $newarray; # this doesn't work :-( as the printf above, any id +eas?

20050213 Janitored by Corion: Added formatting

Replies are listed 'Best First'.
Re: printf and variables
by friedo (Prior) on Feb 13, 2005 at 21:03 UTC
    That doesn't work because printf requires two arguments, a format string and a list of variables to coerce into the format. If you say printf $newarray (a rather odd choice of variable name, BTW) then you're only sending one argument to printf. You can do what you want by simply doing:

    my $format = '%11s %3d %5.1f\n'; printf $format, 'Hello there', 123, $pi;
      friedo / zaxo thanks....... much appreciated
Re: printf and variables
by Zaxo (Archbishop) on Feb 13, 2005 at 21:03 UTC

    That's an odd thing to do, but it will work if you seperate all the array elements with newlines and say, printf split /\n/, $newarray;.

    It will work better if you use a real array,

    my @newarray = ('Hello there %3d %5.1f\n'); push @newarray, 123, $pi; printf @newarray;

    I absorbed the constant greeting into the format string.

    After Compline,
    Zaxo

      This is close to how I quite often do this very thing:

      my $format = "Hello there %3d!"; my @data = (123); if (defined $pi) # if we've calculated pi ... { $format .= " %5.1f"; push @data, $pi; } printf "$format\n", @data;

      Very useful to be able to do this. The above example specifically doesn't seem too useful, but the overall idea is quite useful. At least to me.

Re: printf and variables
by m-rau (Scribe) on Feb 13, 2005 at 21:12 UTC