categorized answer
QandAEditors
From [isbn://0937175641|Programming Perl (1st Ed)] written by Larry Wall and [merlyn|Randal Schwartz] ...<p>
<dl><dd><code>
perl -e 'srand;' \
-e 'rand($.) < 1 && ($it = $_) while <>;' \
-e 'print $it' FILE
</code></dd></dl><p>
This procedure selects a line at random from a file, using just one pass over the file and without knowing in advance the number of lines. It works by calculating the probability that the current line (indicated by the <code>$.</code> variable) would be selected if this line were the last line in the file. The first line is selected with a probability of 100%, but the second line has a 50% chance of replacing the first one, the third line a 33% chance of replacing one of the first two, and so on.
1910