[Wellington-pm] Select at random from a list

Daniel Pittman daniel at rimspace.net
Sun Jul 16 17:33:02 PDT 2006

Philip Plane <philip at xinqu.net> writes:
> On Sat, 15 Jul 2006, Jacinta Richardson wrote:
>> 	$mp3 = $playlist[int(rand(scalar(@playlist)))];
>> can also be written as:
>> 	$mp3 = $playlist[ rand(@playlist) ];
> Yes, I could do that. Turns out I can also do:
>  $mp3 = $playlist[rand @playlist];

As usual the brackets, on a built-in function, are optional in Perl.
Syntax sugar, and the occasional conveniente.

> 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];

Actually, you just /introduced/ an off-by-one bug into your code. 

There are two ways to get the number of elements in a Perl array:

    my @foo = (1, 2, 3);
    print "true\n" if $#foo == 2;
    print "true\n" if scalar @foo == 3;

Both of those statements will print: $#array returns the index of the
last element of the array -- the number of items less one.

Evaluating an array is scalar context, on the other hand, gives the much
nicer count of elements.

'rand' returns a number that is *less* than the value of the argument

Your amended code is incorrect because the value returned by random,
plus one, is mismatched with the array reference values, which are zero

Rather than correctly returning zero through N minus one, your code is
now off by one -- too many. :)

Digital Infrastructure Solutions -- making IT simple, stable and secure
Phone: 0401 155 707        email: contact at digital-infrastructure.com.au

More information about the Wellington-pm mailing list