Recipe 8.7. Randomizing All Lines (Perl Cookbook)

Perl Cookbook

Perl CookbookSearch this book
Previous: 8.6. Picking a Random Line from a FileChapter 8
File Contents
Next: 8.8. Reading a Particular Line in a File
 

8.7. Randomizing All Lines

Problem

You want to copy a file and randomly reorder its lines.

Solution

Read all lines into an array, shuffle the array using the algorithm from Recipe 4.17, and write the shuffled lines back out:

# assumes the &shuffle sub from Chapter 4
while (<INPUT>) {
    push(@lines, $_);
}
@reordered = shuffle(@lines);
foreach (@reordered) {
    print OUTPUT $_;
}

Discussion

The easiest approach is to read all lines into memory and shuffle them there. Because you don't know where lines start in the file, you can't just shuffle a list of line numbers and then extract the lines in the order they'll appear in the shuffled file. Even if you did know their starts, it would probably still be slower because you'd be seeking around in the file instead of simply reading it from start to finish.

See Also

Recipe 2.7; Recipe 2.8; Recipe 4.17


Previous: 8.6. Picking a Random Line from a FilePerl CookbookNext: 8.8. Reading a Particular Line in a File
8.6. Picking a Random Line from a FileBook Index8.8. Reading a Particular Line in a File

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.