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

Hello Monks...

Some interesting stuff in Super Search about this, but nothing directly applicable I could see.
Assume an array like
my @colors = ("yellow", "blue", "red")
Is there a convenient way to choose a single element of the array randomly?
my @colors = ("yellow", "blue", red") my $color = some_cool_perl_random_thingie(@colors); print "The surprise color is $color"

Replies are listed 'Best First'.
Re: Choose random element of array?
by tinita (Parson) on May 28, 2004 at 16:27 UTC
    my $color = $colors[rand @colors];
    perldoc -f rand -> perlfunc
Re: Choose random element of array?
by mojotoad (Monsignor) on May 28, 2004 at 16:32 UTC
    Or, if you want "pick once" functionality (consumes the original array):
    my $color = splice(@colors, rand @colors, 1);

    Cheers,
    Matt

      As mojotoad points out, when you need that "pick once" functionality from the array, splice() works wonders.. (in the example below, the @testarray has 1052 elements, so the counter runs out at 1051:)

      use strict; my $counter = 0; my $randstring; my @testarray = ( 'a' .. 'z', 'A' .. 'Z', '0' .. '999' ); do { $randstring .= splice(@testarray, int rand @testarray, 1); ++$counter; } until $counter == 1051; print "$randstring\n";


        Nice snippet. I couldn't help but point out that you already have a built-in counter -- the number of elements in the array. Reworking your example a bit, we get the following:
        use strict; my $randstring; my @testarray = ( 'a' .. 'z', 'A' .. 'Z', '0' .. '999' ); $randstring .= splice(@testarray, rand @testarray, 1) while @testarray; print "$randstring\n";
        Cheers,
        Matt

        What you have there is essentially a shuffle and join. Using splice to shuffle is tempting, but inefficient. perlfaq4 already covers this topic well, and List::Util's shuffle makes it convenient.

Re: Choose random element of array?
by kesterkester (Hermit) on May 28, 2004 at 16:31 UTC
    Something like this will work:

    int rand (@arr) will get you a random index for in @arr's range, and then you can just print it out with  $arr[int rand (@arr)]

    E.G.:

    perl -le '@arr = 10..19; print $arr[int rand@arr]'