Hi, your problem description is not very clear. I think you are saying that you want to be able to handle arrays of varying lengths with a single sprintf statement. If so, you can always use the result of an expression as the format:

use strict; use warnings; my @slow_day = ( 4, 1..4 ); my @busy_day = ( 12, 1..12 ); for my $report ( \@slow_day, \@busy_day ) { my ( $total, @sales ) = @{ $report }; my $fmt = 'Total: $%2d Sales:' . ' $%.02f' x scalar(@sales); print sprintf($fmt, $total, @sales), "\n"; } __END__
Output:
$ perl 1223893.pl Total: $ 4 Sales: $1.00 $2.00 $3.00 $4.00 Total: $12 Sales: $1.00 $2.00 $3.00 $4.00 $5.00 $6.00 $7.00 $8.00 $9.0 +0 $10.00 $11.00 $12.00
Similarly you can examine the list and use the longest element length as a padding value, etc.

As to your second question: What happens when perl ... "runs out" of parameters (there are more variables to print than parameters in the format) ... Well, what happens when you try it? You can just use a one-liner for that:

$ perl -Mstrict -wE 'say sprintf("%s", qw/two strings/);'

Hope this helps!


The way forward always starts with a minimal test.

In reply to Re: sprintf and arrays of unknown (in advance) length by 1nickt
in thread sprintf and arrays of unknown (in advance) length by Anonymous Monk

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.