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

Hi

I want to use sprintf for generating a string that contains a repeated set of arguments, and wanted to not have to specify the arguments multiple times, I found a way to do it (using %[n]$s), and the example below works.

perl -e 'printf q{%2$s %1$s - %2$s %2$s}, "world", "hello"'

The problem is I haven't found any mention of it in the camel book, and a quick search here didn't turn up anything. Is it safe to use this, or is this something that is not likely to be universally implemented?. If it is safe to use, why isn't it mentioned in the camel book?

Prowler
 - Spelling is a demanding task that requies you full attention.

Replies are listed 'Best First'.
Re: (s)printf using argument selection
by geekphilosopher (Friar) on Feb 23, 2007 at 07:37 UTC

    The Camel doesn't fully spell out the use of every built-in function. From perldoc sprintf:

    Between the % and the format letter, you may specify a number of additional attributes controlling the interpretation of the format. In order, these are: * format parameter index An explicit format parameter index, such as 2$. By default sprintf will format the next unused argument in the list, but this allows you to take the arguments out of order, e.g.:

    printf '%2$d %1$d', 12, 34; # prints "34 12" printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1"

      And that's what I get for ignoring the 'out-dated' bit at sprintf. Thanks - full speed ahead!

      Prowler
       - Spelling is a demanding task that requies you full attention.