Skip to Main Content
Perl Cookbook
book

Perl Cookbook

by Tom Christiansen, Nathan Torkington
August 1998
Intermediate to advanced content levelIntermediate to advanced
800 pages
39h 20m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook

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 Section 4.17, and write the shuffled lines back out:

# assumes the &shuffle sub from Chapter 4
while (<INPUT>) {
    push(@lines, $_);
}
fisher_yates_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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl Best Practices

Perl Best Practices

Damian Conway
Mastering Perl

Mastering Perl

brian d foy
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington

Publisher Resources

ISBN: 1565922433Supplemental ContentCatalog PageErrata