[Wellington-pm] Select at random from a list

Jacinta Richardson jarich at perltraining.com.au
Sun Jul 16 18:03:40 PDT 2006


Philip Plane wrote:

> Yes, I could do that. Turns out I can also do:
> 
>  $mp3 = $playlist[rand @playlist];

I just assumed you liked your parentheses.  :)

> And even better I can correct for the off by one bug that I'd deliberately
> put in to see if you were all awake :)
> 
>  $mp3 = $playlist[rand @playlist +1];

Daniel has already pointed out why this doesn't do what you wanted it to.  The
other issue I'll raise here is one of precedence.

Is the above syntactically the same as:

    $mp3 = $playlist[rand(@playlist) +1];

or

    $mp3 = $playlist[rand (@playlist+1)];

If you can't tell, just by looking, then you ought to put parentheses in.

Be aware that these are not the same things.  rand(x+1), gives you a number
between 0 and x+1, whereas rand(x)+1 gives you a number between 1 and x+1.

Predecence is something to always watch out for.  Particularly for anyone else
who has to maintain your code.

	J

-- 
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |


More information about the Wellington-pm mailing list