Recipe 8.6. Picking a Random Line from a File (Perl Cookbook)
csg.sph.umich.edu·15h
Flag this post

Problem

You want to return a random line from a file.

Solution

Use rand and $. (the current line number) to decide which line to print:

srand;
rand($.) < 1 && ($line = $_) while <>;
# $line is the random line

Discussion

This is a beautiful example of a solution that may not be obvious. We read every line in the file but don’t have to store them all in memory. This is great for large files. Each line has a 1 in N (where N is the number of lines read so far) chance of being selected.

Here’s a replacement for fortune using this algorithm:

$/ = "%%\n";
$data = '/usr/share/games/fortunes';
srand;
rand($.) < 1 && ($adage = $_) while <>;
print $adage;

If you know line offsets (for instance, you’ve created an index) and the number of lines, y…

Similar Posts

Loading similar posts...