This solution while not the most obvious is probably the best because it doesn't
require you to store the entire file in memory. Instead it reads in each line and chooses whether or not that line will be stored as the random line.
$. is a special variable that stores the current line number you are on starting with 1.
To show that this works we'll walk through an example reading line 1 to 3.
1. read line 1
2. rand(1)<1 #100% chance it's true if we had just one line
3. read line 2
4. rand(2)<1 #50% chance that line 2 replaces line 1 as the random
+line.
5. read line 3
6. rand(3)<1 #1/3 chance that line 3 replaces the currently chosen
+line
srand;
open FILE, "<filename" or die "Could not open filename: $!\n";
rand($.)<1 and ($line=$_) while <FILE>;
close FILE;
print "Random line is $line\n";
|