in reply to Creating a random generator

The key statement for generating random numbers is rand. By itself, it generates a fraction which is at least 0 and less than 1. Given a number, as in rand(6), it generates an integer which is at least 0 and less than the number it was given (0 to 5 in this case).

For the example you've given with colors, the code would be:

my @colors = qw(red yellow green cyan blue magenta white gray black); print $colors[rand @colors], "\n";
The first line makes a list of available choices and the second creates a number from 0 to (the number of options - 1), then prints the item at that position in the list. (List elements are numbered starting at 0 rather than 1, so this can produce any element in the list.)

Replies are listed 'Best First'.
Re^2: Creating a random generator
by grinder (Bishop) on Sep 06, 2007 at 14:41 UTC
    Given a number, as in rand(6), it generates an integer which is at least 0 and less than the number it was given (0 to 5 in this case)

    Almost, but not quite.

    % perl -le 'print rand(6)' 4.45325434943245

    This will take the number between 0 and less than 1 and multiply it by 6, nearly always leaving stuff behind the decimal point.

    If you really don't want the fractional part you have to shave it off with either int($num) or sprintf('%.0f', $num). In the present case it'll work just fine, since Perl will Do The Right Thing and treat the number as an integer anyway, in order to use it as an index into the array. But were the OP to print the number itself, they may be surprised by the result.

    • another intruder with the mooring in the heart of the Perl