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

Dear Monks

I have the following print statement which looks just a little bit odd to me
$a = 10 ; $b = 123456 ; printf "%${a}d", $b ; # instead of printf "%10d", $b ;
Is this the correct way to use printf ?

Thanks
LuCa

Replies are listed 'Best First'.
Re: printf with variable display width
by QM (Parson) on Jun 14, 2006 at 16:28 UTC
    That's one way to do it. I prefer the clearer method shown at sprintf: (minimum) width.

    The equivalent would then be:

    printf "%*d", $a, $b;

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Re: printf with variable display width
by ikegami (Patriarch) on Jun 14, 2006 at 16:43 UTC

    If you're accepting $a from an untrusted source — aren't they all? — don't forget to validate it.

    Don't use $a and $b as general purpose variables. They are special and reserved for sort callbacks.

Re: printf with variable display width
by lukeyboy1 (Beadle) on Jun 14, 2006 at 16:24 UTC
    Yes, it does work. Try this, for example:

    $a = 1.2; $b = 123456 ; printf "%${a}f", $b ; # instead of printf "%1.2f", $b ;


    to see it use the equivalent of %1.2f (quite why you'd want this, is another matter...!).

    Cheers, -L-
Re: printf with variable display width
by dsheroh (Monsignor) on Jun 14, 2006 at 16:27 UTC
    It is a correct way to use it, just so long as it does what you want it to. I wouldn't say it's the correct way, as there are times when it's appropriate and times when it's overkill. TIMTOWTDI and all.