[This is another bonus, mid-week item since it’s so short and probably mostly useless as a tweak to what you already do.]
Perl 5.14 changes srand to return the seed that it used to start the pseudorandom number generator that gives you numbers through rand. There are plenty of interwebs that will explain the difference between real randomness and the sort that you get from computers, but for this item, suffice it to say that the numbers you get from perl are completely deterministic. If you start with the same seed, you get the same sequence.
You may have never seen srand
because your first call to rand
does it implicitly for you. That’s not very good if you want to reply the same sequence.
You can call srand
with a seed already (prior to Perl 5.14), and if you give it the same seed you get the saem sequence:
$ perl -le 'srand( shift ); print rand for 1 .. 5' 10 0.878851122762175 0.795806622921617 0.480827281057042 0.525673258208322 0.459162474505394 $ perl -le 'srand( shift ); print rand for 1 .. 5' 10 0.878851122762175 0.795806622921617 0.480827281057042 0.525673258208322 0.459162474505394 $ perl -le 'srand( shift ); print rand for 1 .. 5' 10 0.878851122762175 0.795806622921617 0.480827281057042 0.525673258208322 0.459162474505394
Change the seed and you get a different sequence:
$ perl -le 'srand( shift ); print rand for 1 .. 5' 42 0.744525000061007 0.342701478718908 0.111085282444161 0.422338957988309 0.0811111711783106 $ perl -le 'srand( shift ); print rand for 1 .. 5' 137 0.470744323291914 0.278795581867115 0.263413724062172 0.646815254210146 0.958771364426031
Now you can call srand
and let it choose the key. This one liner uses the key you provide or the empty list, which lets srand
decide which seed to use:
$ perl5.13.5 -le 'my $s = srand( shift // () ); print "seed is [$s]"; print rand for 1..5' 54 seed is [54] 0.194152704048069 0.797787049642892 0.972432032964331 0.00858859540580426 0.939341932430654 $ perl5.13.5 -le 'my $s = srand( shift // () ); print "seed is [$s]"; print rand for 1..5' 137 seed is [137] 0.470744323291914 0.278795581867115 0.263413724062172 0.646815254210146 0.958771364426031 $ perl5.13.5 -le 'my $s = srand( shift // () ); print "seed is [$s]"; print rand for 1..5' seed is [0 but true] 0.17082803610629 0.749901980484964 0.0963716556235674 0.870465227027076 0.577303506795108 $ perl5.13.5 -le 'my $s = srand( shift // () ); print "seed is [$s]\n"; print rand for 1..5' 0 seed is [0 but true] 0.17082803610629 0.749901980484964 0.0963716556235674 0.870465227027076 0.577303506795108
Curiously, it appears that the default seed is 0 but true
, which is the number 0 and a true value at the same time (Item 7. Know which values are false and test them accordingly.).
Is there much chance of this being useful to you? Probably not; if it were you were probably already giving srand
its seed.