in reply to Re: How do I pick a random element from an array?
in thread How do I pick a random element from an array?

Wrong.

That will never pick the last element.

#!/usr/bin/perl use strict; use warnings 'all'; my @array = qw /first middle last/; my $count = 0; my $sec = 100; $SIG {ALRM} = sub { die "Ran for $sec seconds, trying $count times and failed.\n" }; alarm $sec; my $randomIndex; do { $count ++; $randomIndex = rand $#array; } until $array [$randomIndex] eq "last"; print "Success after $count tries.\n"; __END__ Ran for 100 seconds, trying 29495241 times and failed.
However, if we change the rand $#array to rand @array, we get:
Success after 2 tries.
or some other small number.

Abigail

Replies are listed 'Best First'.
Re: Re: Answer: How do I pick a random element from an array?
by Anonymous Monk on Sep 19, 2003 at 07:26 UTC