When rand isn't random
In spite of having programming Perl mostly full time for the last 12 years, I still find myself learning new things about how Perl works (like the time I discovered the arcane apostrophe package separator when trying to add a possessive 's' on the end of a variable in an interpolated string).
Yesterday yielded a similar epiphany when I realized how rand, srand and fork were interacting in our e-commerce application at $work. Consider the following one-liner:
perl -le 'for(1..2) { fork or do { print int rand 100; exit } }'
This prints two random numbers between 0 and 99. Simple. Now, consider this slightly different example:
perl -le 'rand; for(1..2) { fork or do { print int rand 100; exit } }'
This prints the same random number between 0 and 99 twice. The reasoning is quite simple but was not obvious to me at first. When rand is first called in a Perl application, srand is implicitly called to seed rand with a different starting number. If this happens prior to a process forking, the same seed is shared by all of the child processes and non-randomness ensues.
