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

Hi - I'm having a problem with the rand function. The code looks like this:
while ($edtpost =~ /\[roll=(\S+?)\]/i) { $seed = $1; if(!$seed || $seed > 12 || $seed < 1) { $seed=6; } srand(); $rndrslt = 0; $rndrslt = int(rand($seed)) + 1; print "$rndrslt\n"; }
where $edtpost is a scalar containg multiple strings such as [roll=1], [roll=2], etc. The problem is, a) the function uses only the first $seed returned - that is, it always uses the same seed, even though $1 SHOULD be replaced. Also, b) the number returned is the same for EVERY iteration of the loop. Suggestions? Thanks in advance

Replies are listed 'Best First'.
Re: rand() problems
by danger (Priest) on Feb 27, 2001 at 10:26 UTC

    Hyperiris, if you want to iterate through regex matches in your while condition you'll need to use the /g modifier. Also, using $seed as a variable name for a variable which isn't being used to seed the srand function (but is instead being used as the rand() argument) only adds confusion. Lastly, unless you have need to reproduce results with a given seed (that is, a seed for the srand() function), then you want to call srand() only once prior to the loop (and with recent perl's, you don't really need to call srand() at all).

    The reason you are getting the same $rndrslt everytime is that your $edtpost string starts with roll=1, setting $seed to 1, and thus your call to int(rand($seed)) + 1 is always going to return 1. Please see the following documents: rand and srand.

Re: rand() problems
by merlyn (Sage) on Feb 27, 2001 at 10:18 UTC
      It doesn't work without the srand, either. I originally didn't have it in there.
        Newer perls call srand() for you implicitly. What version are you using?