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

Hi monks,

I was searching for a while but I cant find any answer.

Is there a possible to make the numbers in the format-string changable?

sprintf "%05i", $myInt;
Instead of the 5 I'd like to be able to put a varibale here but this fails allready because the 'i' for integers would be recognized as part of the variable:
$int = 5; sprintf "%0$inti", myInt;
Is there a solution beside a long switch?

Thanks in advance, Carl

Replies are listed 'Best First'.
Re: printf & sprintf: variable number formats
by duff (Parson) on Jan 06, 2004 at 16:35 UTC

    There are several ways to do this. Here are two:

    $int = 5; sprintf "%0${int}i", $myint; $int = 5; sprintf "%0*i", $int, $myint;
      wow,

      that was fast,
      thanks,
      Carl

Re: printf & sprintf: variable number formats
by dragonchild (Archbishop) on Jan 06, 2004 at 16:35 UTC
    $int = 5; sprintf "%0${int}i", $myInt;

    You were missing the curly-braces around the variable name.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Re: printf & sprintf: variable number formats
by flounder99 (Friar) on Jan 06, 2004 at 19:34 UTC
    A simple concat works,
    $int = 5; printf "%0" . $int . "i", $myInt;
    it just isn't as pretty. But it also works with constants
    use constant COLWIDTH => 5; $int = 5; printf "%0" . COLWIDTH . "i", $myInt;

    --

    flounder

      Good point. I should probably have mentioned that very thing about printf "%0*i", $int, $myint; too

Re: printf & sprintf: variable number formats
by Not_a_Number (Prior) on Jan 06, 2004 at 19:01 UTC

    Just a small additional remark. It would appear that "%d" is preferable to "%i", based on this extract from perldoc sprintf:

    Finally, for backward (and we do mean "backward") compatibility, Perl permits these unnecessary but widely-supported conversions:
    %ia synonym for %d
    (etc)

    So prefer sprintf "%0${int}d" or whatever...

    dave

Re: printf & sprintf: variable number formats
by Roger (Parson) on Jan 07, 2004 at 14:48 UTC
    TIMTOWTDI.

    use strict; use warnings; use constant LEN => 5; my $n = 12; my $str = '0' x (LEN-length($n)) . $n; print "$str";
    Output is as expected -
    00012