On Fri, Mar 22, 2002 at 07:03:04PM -0700, Troy Sniff wrote: > Here is what I am trying to do. > > I will be running a prepare statement on a table. That query might > return any number of rows from the table. > > From those rows, I want to randomly grab a certain number of them to be > used. > > For example, let's say my query returns 134 rows. I want to then > randomly pick 50 (or some number) of them to be used. > > I have thought of pulling each row into an array and creating an array > of arrays. From there I can randomly grab a certain number. > > Does anyone know of a good way of doing this?
Putting all the rows in an array and then selecting a random subset will work, but if the total number of rows is large and the desired number of rows is small, you may want to avoid using the memory to store all the rows at once. This approach, which selects some number of rows at random with the rows coming in one at a time, is based on the code to select a random line from a file from perlfaq5. my $count = 50; my $total = 0; while (my(@row) = $sth->fetchrow_array()) { push @rows, [@row] if rand() < ($count / ++$total) if (@rows > $count) { splice(@lines, rand($#rows), 1); } } Ronald