--------------------------------------------------------------------
4.50: How do I select a random element from an array?
Use the "rand()" function (see "rand" in perlfunc):
$index = rand @array;
$element = $array[$index];
Or, simply:
my $element = $array[ rand @array ];
--------------------------------------------------------------------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
Wouldn't this be safer?
$element = $array[ int( rand @array ) ];
-Mithun
>> � � � � � � my $element = $array[ rand @array ];
m> Wouldn't this be safer?
m> $element = $array[ int( rand @array ) ];
why do you think it would be safer? think about this a bit. what kind of
value is needed for an array index? what happens if you do $array[1.34]?
would perl blow up? would it spit out a warning? did you try the code in
the FAQ? when you have an answer, post again, and we will reply as
needed.
uri
--
Uri Guttman ------ u...@stemsystems.com -------- http://www.sysarch.com --
----- Perl Code Review , Architecture, Development, Training, Support ------
--------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com ---------
> On Nov 4, 11:00�am, PerlFAQ Server <br...@theperlreview.com> wrote:
> > � � � � � � my $element = $array[ rand @array ];
> Wouldn't this be safer?
>
> $element = $array[ int( rand @array ) ];
Array and slice indices are already converted to integers for you. :)
I had no idea that it did that until I tried the code in the FAQ. The
reason I asked this question is because perlfunc rand() says "Apply int
() to the value returned by rand() if you want random integers instead
of random fractional numbers". Always having used integers for an
array index/slice, I assumed I would want a random integer instead of
a fraction. Anyways, now I know that Perl handles that internally.
Now an obvious question, and answer easy enough to find for each who
is interested, but maybe more efficient if answer is added
to the faq:
HOW does the (real) index get converted to integer subscript?
Floor, Ceiling, some .5-rule, or what?
David