10 Jan 2014

Perl: Randomize-Shuffle Lines of a Text File

Perl script:

#!/usr/bin/env perl  
use strict;  
use warnings;  
use File::Slurp;  
use Try::Tiny;  

# Set the random seed  
srand (time ^ $$ ^ unpack "%L*", 'ps axww | gzip');  

unless ( @ARGV == 1 ) {  
  print "\nUsage: $0 filename > newfilename\n\n";  
  exit;  
}  

try {  
  my @lines = read_file( $ARGV[0] );  
  # Get random lines, write 'em out, mark 'em done.  
  while ( @lines ) {  
    my $line = splice(@lines, rand @lines, 1);  
    print $line;  
  }  
} catch { warn "*** $_"; };