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!


In reply to Interpret a string that contains strings by bArriaM

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.