| Programming C# C++ (7) Delphi (618) Java (8) JavaScript (30) perl (9) mysql (3) perl CGI (3) php (4) VBScript (1) Visual Basic (1) |
Generating a random number
Question: I need to generate a random number between 1 and 100. How do I do this with perl?Answer: You need two functions: srand() to initialize the random generator. This needs to be called only once at the beginning of your program. You may pass an argument to initialize srand, if you don't it will use a semi-random value based on the current time and process ID, among other things. If you think that you need really random random numbers e.g. for cryptography, then you should see the Math::TrulyRandom module in CPAN.After initializing, use rand() each time you need a random number. rand() by default will return a value >= 0 and < 1. Use rand(100) to get a value >=0 and < 100. Your code would look like this:
Comments:
|