## WeBWorK Problems

### how to pick a random element from a list ### how to pick a random element from a list

by Siman Wong -
Number of replies: 1
I would like to pick out a random element from a list, like this:

DOCUMENT();

"PG.pl",

"PGbasicmacros.pl",

"PGchoicemacros.pl",

"PGauxiliaryFunctions.pl"

);

$l = (-1,-2,-3,-4,-5,-6);$j = random(0,3,1);

$k =$l->[$j]; TEXT(EV3(<<'EOT')); print this:$k end of print

EOT

ENDDOCUMENT();

When I ran this in PGLabs I only get as output

print this: end of print

I clearly do not understand how array works in PG/Perl; your help and assistance is most appreciative. ### Re: how to pick a random element from a list

by Gavin LaRose -
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