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

Hi, I want to dynamically create the format of the printf function. I want to create a "printToFile" function that can be dynamic, so that it can handle any number of given arguments to write to the file, in the specified format.

I have this code:

sub printfToFile { my $file = shift; my $format = shift; my $arrayCount = @_; my $formatString; for (my $r = 1;$r <= $arrayCount; $r++) { $formatString = $formatString.'$format '; } $formatString = trim( $formatString ); $formatString = $formatString.'\n'; open IO, ">>$file" or die "Cannot open $file for output: $!\n+"; # printf IO "$format $format\n", @_; printf IO "$formatString", @_; close IO; }

The commented out line works perfectly, the printf function will write the 2 strings in the file, with the $format that I specified when calling the function

printfToFile( $logfile, '%-22s', $ifName, $ifLease );

Now, I want to dynamically create that format line, and with the previous code, the $formatString value is identical to this: $format $format\n

Why would printf print this to the file: $format $format\n$format $format\n, etc.

Thank you very much!

Replies are listed 'Best First'.
Re: Interpret a string that contains strings
by choroba (Cardinal) on Nov 21, 2015 at 22:41 UTC
    Single quotes don't interpolate variables. '$format ' (see line 9) contains a dollar sign, and letters f, o, r, m, a, t, and a space.
    $formatString = "$formatString$format ";

    Similarly, use "\n" instead of '\n' on line 13.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      I shouldn't drink wine and code at the same time... Thank you Sir, it works like a charm after the changes, I wanted to make it too complicated!

      sub printfToFile { my $file = shift; my $format = shift; my $arrayCount = @_; my $formatString; for (my $r = 1;$r <= $arrayCount; $r++) { $formatString = $formatString."$format "; } $formatString = trim( $formatString ); $formatString = $formatString."\n"; open IO, ">>$file" or die "Cannot open $file for output: $!\n+"; printf IO "$formatString", @_; close IO; }
Re: Interpret a string that contains strings
by BillKSmith (Monsignor) on Nov 22, 2015 at 03:45 UTC