Perl | srand() Function
Last Updated :
07 May, 2019
The srand() function in Perl helps rand() function to generate a constant value each time the program is run.
This srand() function uses the same parameter each time the rand() function is called for getting constant random value.
Syntax: srand(seed)
Parameters:
seed : It is an integer value.
Return: This function does not return any value.
Example 1:
srand (5);
print ( "The first random number is " , rand (), ".\n" );
srand (5);
print ( "The second random number is " , rand (), ".\n" );
srand (5);
print ( "The third random number is " , rand (), ".\n" );
srand (5);
print ( "The fourth random number is " , rand (), ".\n" );
|
Output:
The first random number is 0.524839579434232.
The second random number is 0.524839579434232.
The third random number is 0.524839579434232.
The fourth random number is 0.524839579434232.
Note: In the above code, it can be seen that the parameter of srand() function is same that is why the rand() function produced the same random value each time it is called.
Example 2:
srand (5);
print ( "The first random number is " , rand (), ".\n" );
srand (6);
print ( "The second random number is " , rand (), ".\n" );
srand (7);
print ( "The third random number is " , rand (), ".\n" );
srand (8);
print ( "The fourth random number is " , rand (), ".\n" );
|
Output :
The first random number is 0.524839579434232.
The second random number is 0.395641888099821.
The third random number is 0.266444196765409.
The fourth random number is 0.137246505430998.
Note: In the above code, it can be seen that the srand() functions are having a different parameter that is why the rand() function produced the different random value each time it is called.
Example 3:
print ( "The first random number is " , rand (), ".\n" );
print ( "The second random number is " , rand (), ".\n" );
print ( "The third random number is " , rand (), ".\n" );
print ( "The fourth random number is " , rand (), ".\n" );
|
Output :
The first random number is 0.241482914266275.
The second random number is 0.821264154368208.
The third random number is 0.870625858233449.
The fourth random number is 0.012084407123389.
Note: In the above code, it can be seen that the srand() functions are not used that is why the rand() function produced the different random value each time it is called.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...