in reply to Re^2: Get CID inline attachments with MIME::Parser
in thread Get CID inline attachments with MIME::Parser

sebastiannielsen:

About srand:

I dont know if this are updated now, but when I first begun learning perl, I noticed that if I would run 2 instances of a script printing a sequence of random digits, both scripts would show the same sequence if not srand; was runned in the beginning. Therefore, I have get used to srand; in the beginning when Im gonna use rand();

A typical random number generator will generate the same sequence of numbers with the same initial state. It can be a blessing or a curse. Be sure to seed your random number generator when you want individual runs to be different. I typically use time for that.

About repeated calls to rand:

The repeated calls to rand is to force leading zeroes in case I get a number like 000001. Perl would normally strip off all leading zeroes leading to strange filenames.

By calling int(rand(10) repeated times, I guarantee that the resulting number will have this number of digits. So if I would want to generate a 10 digit number, thats ALWAYS 10 digits, even if the number coming out is 1, I would run:

$number = int(rand(10)).int(rand(10)).int(rand(10)).int(rand(10)).int( +rand(10)).int(rand(10)).int(rand(10)).int(rand(10)).int(rand(10)).int +(rand(10));
That would force the number to the string "0000000001" if it gets that number, and not "1".

A simpler method would be:

$number = sprintf "%010u", int(rand(10000000000));

...roboticus

Replies are listed 'Best First'.
Re^4: Get CID inline attachments with MIME::Parser
by Marshall (Canon) on Nov 28, 2010 at 23:24 UTC
    A typical random number generator will generate the same sequence of numbers with the same initial state. It can be a blessing or a curse. Be sure to seed your random number generator when you want individual runs to be different. I typically use time for that.

    Except with ancient Perl (5.004), calling srand() yourself is not necessary. rand() will call srand() on the first call to rand(). The seed value used is a function of time, PID and memory allocation so typically what rand()will do itself is better than what calling srand() yourself would do. srand rand

    Basically to get the same set of random numbers for a new run you have to keep specifying the same seed in an explicit call to srand() at the start of the run. I do that when I am debugging and want to get the same numbers so that some error case is reliably repeatable.