Usage: ChooseFrom(@MyArray);
Or:
ChooseFrom( my("Jack Daniels", "Jim Bean", "Johny Walker") );</div> <CODE> sub ChooseFrom{ return $_[ int( rand() * ( $#_ + 1 ) ) ]; }

Replies are listed 'Best First'.
RE: Randomly Choose an Element from an Array
by merlyn (Sage) on Aug 27, 2000 at 15:46 UTC
      Here is something more complicated:

      The first function (randl) generates a random number according to the logarithmic scale; it "favors" smaller numbers. The BiasedChooseFrom function picks an element; but it favors the smaller numbers.
      sub randl{ return int( -$_[1] * log( $_[0] * rand() ) ); } sub BiasedChooseFrom{ return $_[ int( randl(4,int($#_/2)) ) ]; }
        Your code continues to scare me. What's with the int functions when subscripting already forces an integer? And why do you continue to use $n * rand() when rand($n) does the same thing? And are you sure your randl function always returns a value within the range of the array subscripts? I think it can return negative numbers at first glance, which would then access the ending array elements overly often.

        In short, thanks for wanting to contribute, but please get a little more Perl experience under your belt, so we don't have to steer others away from your code. If you want, please preview your post by emailing it to me, and I'll be happy to provide you with suggestions.

        -- Randal L. Schwartz, Perl hacker

RE: Randomly Choose an Element from an Array
by t0mas (Priest) on Aug 27, 2000 at 22:46 UTC
    If I were to write a sub that choose one from ("Jack Daniels", "Jim Bean", "Johny Walker") it would be sub PickTheRightOne{ return $_[0] }; since I wouldn't want rand to choose for me in this case ;-)

    /brother t0mas
      Which one would be the right one, then? Jack Daniels?

      Sinan
        I don't want to start a religous war about it, but IMO: Yes :)

        /brother t0mas
      Oooops... English mistake! :-(

      Let me rename it as PickAnyOneFrom, in that case.:-)

      Sinan