| Newsgroups |
perl.cvs.perlfaq |
| Message-ID |
<[email protected]> |
cvsuser 02/06/20 21:28:27
Modified: . perlfaq5.pod
Log:
* How do I select a random line from a file?
+ mentioned Tie::File
+ added reference to Knuth's demonstration of the algorithm
Revision Changes Path
1.20 +7 -4 perlfaq/perlfaq5.pod
Index: perlfaq5.pod
===================================================================
RCS file: /cvs/public/perlfaq/perlfaq5.pod,v
retrieving revision 1.19
retrieving revision 1.20
diff -u -w -r1.19 -r1.20
--- perlfaq5.pod 17 Jun 2002 04:44:52 -0000 1.19
+++ perlfaq5.pod 21 Jun 2002 04:28:27 -0000 1.20
@@ -1,6 +1,6 @@
=head1 NAME
-perlfaq5 - Files and Formats ($Revision: 1.19 $, $Date: 2002/06/17 04:44:52 $)
+perlfaq5 - Files and Formats ($Revision: 1.20 $, $Date: 2002/06/21 04:28:27 $)
=head1 DESCRIPTION
@@ -970,14 +970,17 @@
=head2 How do I select a random line from a file?
+You can use the Tie::File method which treats the entire file
+as an array. Simply access a random array element.
+
Here's an algorithm from the Camel Book:
srand;
rand($.) < 1 && ($line = $_) while <>;
-This has a significant advantage in space over reading the whole
-file in. A simple proof by induction is available upon
-request if you doubt the algorithm's correctness.
+This has a significant advantage in space over reading the whole file
+in. You can find an explanation of this method in The Art of Computer
+Programming, Volume 2, Section 3.4.2 by Donald Knuth.
=head2 Why do I get weird spaces when I print an array of lines?