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 | |
by bArriaM (Novice) on Nov 21, 2015 at 23:00 UTC | |
|
Re: Interpret a string that contains strings
by BillKSmith (Monsignor) on Nov 22, 2015 at 03:45 UTC |