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

Hi,

I want to create a random figure between 1 and 9999, but if it's under 4 chars long, I want it to add preceeding zeros (e.g. 0039).

I tried :

$conduit_random = ("%04d",int(rand(9999)));

and although it doesn't give an error it doesn't work either! :(

Is it possible to do it this way or have I got the wrong end of the stick?

Cheers!

Replies are listed 'Best First'.
Re: Formatting randomised data
by davidrw (Prior) on Jun 19, 2005 at 19:39 UTC
    Very close -- I think you meant: $conduit_random = sprintf("%04d",int(rand(9999)));

    What you had was the equivalent of just $conduit_random = int(rand(9999)); For reference, compare these:
    perl -le '$x = (1,2); print $x'; # prints 2 perl -le '($x) = (1,2); print $x'; # prints 1
Re: Formatting randomised data
by thundergnat (Deacon) on Jun 19, 2005 at 19:40 UTC

    Very close. You need to add sprintf.

    $conduit_random = sprintf("%04d",int(rand(9999)));
        my $random = sprintf "%04d", 1 + rand 9999

        per spec :)

        the lowliest monk

      A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Formatting randomised data
by Manawydan (Initiate) on Jun 19, 2005 at 20:59 UTC

    Thanks for all the speedy replies and the help!

    I thought that I could only use sprintf when displaying/exporting the data - didn't realise that I could use it in this way.

    Thanks again! :)

      I thought that I could only use sprintf when displaying/exporting the data
      No, that must be printf you're thinking of. printf actually prints the resulting data (except that it ignores $\), while sprintf just returns the value, ready to store into a variable, for example.
Re: Formatting randomised data
by ambrus (Abbot) on Jun 20, 2005 at 09:18 UTC
    $conduit_random = sprintf("%04d", 1 + int(rand(9999)));

    You need the 1 +, as you won't get 9999 otherwise.