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

Hi Monks Is it possible to pick a number among the pool randomly, something like this @arr = (1,2,13,40,5,6,7,100,34,); $num = rand @arr; I know the answer which i get from the above code is wrong but is there a other way to find do the job. Sid

Replies are listed 'Best First'.
Re: Randomly picking numbers
by gellyfish (Monsignor) on May 05, 2005 at 09:55 UTC

    What you are looking for is:

    $num = $arr[rand @arr];

    /J\

Re: Randomly picking numbers
by trammell (Priest) on May 05, 2005 at 14:42 UTC
    One method I don't see mentioned above is to shuffle the list, then shift the values off as you need them:
    use List::Util 'shuffle'; @arr = shuffle(@arr); my $num = shift @arr;
    This will move a random number from @arr into $num, which may or may not be what you want. It will also shuffle the contents of @arr, so caveat emptor.
Re: Randomly picking numbers
by chanakya (Friar) on May 05, 2005 at 12:27 UTC
    another way of getting random number
    @arr = (1,2,13,40,5,6,7,100,34,); print $arr[int rand(@arr)]."\n";
    !!@!!
    May the force be with you!!

      You don't need the int as the subscript is always an integer therefore the index is implicitly converted before being used.

      /J\

        ...the index is implicitly converted before being used.

        ...and it does so via truncation:

        % perl -le 'print +(0, 1)[0.999999]' 0
        as opposed to rounding, and that's why it works so well in $arr[rand @arr].

        the lowliest monk

Re: Randomly picking numbers
by kprasanna_79 (Hermit) on May 05, 2005 at 11:31 UTC
    Hai,
    Check this link rand or perldoc -q rand in ur box
    --prasanna.k