WeBWorK Problems

how to pick a random element from a list

Re: how to pick a random element from a list

by Gavin LaRose -
Number of replies: 0
Hi Siman,

The problem is that Perl uses
@l = (-1,-2,-3,-4,-5,-6);
for arrays (note the leading @, not $) and
$l[$j]
for array elements (note the $l in this case, and square brackets).

The notation
$l->[$j]
is used to dereference array references. Thus if we define
$lRef = [-1,-2,-3,-4,-4,-6];
which is a reference to an array, we can get elements from it with
$lRef->[$j]

All that said, we can also use random to generate negative values:
$k = random(-6,-1,1);
which will have the same result as the intent of the sample code above.

Gavin