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

I'm performing a lengthy computation that uses a lot of calls to rand, and I want to be able to pause the computation and resume it again later (using Storable or some other serialization). The process starts with a random seed that I provide, so that I can reproduce interesting results later. I want the results to be the same for a given initial random seed regardless of whether I paused/resumed the computation, so I need to somehow save a random seed in my serialization.

The only reasonable* solution I could think of was something along these lines:

## either load the saved random seed and state data from the ## serialization (resume a paused compuatation), or start with ## new state data and the given random seed (start new ## compuation) my ($foo, $bar, $random_seed) = deserialize('saved') || initial_values(); while (1) { srand($random_seed); ## some crunching on $foo, $bar, using lots of rand() ## decide what the next iteration's seed will be $random_seed = int rand( 2 << 31 ); if (check_for_user_interrupt()) { ## save state, along with the seed for next iteration serialize('saved', $foo, $bar, $random_seed); exit; } }
I use rand to generate a new seed for the next iteration, so it can be saved after any iteration. As soon as I wrote srand inside my while loop, red flags popped up in my head. The srand perldoc says:
Do not call srand() multiple times in your program unless you know exactly what you're doing and why you're doing it.
... but I wonder if I really know exactly what I'm doing ;). I found at least one post regarding multiple srand calls, but in that case the poster was using something like time ^ $$ to re-seed within a very fast loop, and expecting different random output for each loop.

What I would really like to know is in what situations is ok to call srand multiple times? Is using a call to rand for a seed considered bad? I can't use any external entropy to re-seed, because I want all the results to be based on the original random seed supplied at the beginning of the computation. Any thoughts on the serialization of randomly-generated state data like this?

*: In the worst case I could always wrap rand, save the original random seed, and simply save the number of times rand was called. Then to resume again, I just reseed, and call rand in void context a whole slug of times. I'd rather not do this!