perl CGI (65)
Visual Basic (3539)
Generating a random number
This article has not been rated yet. After reading, feel free to leave comments and rate it.
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: