2.7. Generating Random NumbersProblemYou want to make random numbers in a given range, inclusive, such as when you randomly pick an array index, simulate rolling a die in a game of chance, or generate a random password. DiscussionThis code generates and prints a random integer between 25 and 75, inclusive: $random = int( rand(51)) + 25; print "$random\n";
The A common application of this is the random selection of an element from an array: $elt = $array[ rand @array ]; And generating a random password from a sequence of characters: @chars = ( "A" .. "Z", "a" .. "z", 0 .. 9, qw(! @ $ % ^ & *) ); $password = join("", @chars[ map { rand @chars } ( 1 .. 8 ) ]);
We use See Also
The Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|