#!perl
# Simple script to rearrange the lines of a text file in "random" order.
# Created 08-2000 by Andrew Greenburg <andrew@analogmarketing.net>.
# Updated 05-2002 by Andrew Greenburg <andrew@analogmarketing.net>.
 
# Get the file names from the argument. Multiple files will be used as a common
# dataset.
if (!$ARGV[0]) {
    die "Usage: $0 <files...>\n";
}
@files = @ARGV;
 
foreach $file (@files) {
    # Read the lines of our file into an array.
    open (FILE, "$file") || die "$file could not be opened.\n";
    while (<FILE>) {
        chomp($_);
        push(@lines, $_);
    }
    close (FILE);
}
 
# Initialize counter.
$secondcount=0;
my %used;
 
# Rearrange the lines. This could probably be more effecient, but it works.
 
# Outside of three loops. Check to see if we're done sorting.
while ($secondcount <= $#lines) {
        # This should be a function, but I'm lazy.
        
        # Initialize these variables here so that our third loop will
        # work. The random number should be less than the total number
        # of lines, because one of our lines is 0.
        $rand = $#lines + 1;
        $oldrand = $rand;
        # Third of three loops. Check to be certain that we didn't get
        # a random number that exceeds our array.
        while ($rand eq $oldrand) {
            # Make a random integer
            $rand = rand($oldrand);
            $rand = int($rand);
        }
        # Read our line from the array into our variable.
        $lineread = $lines[$rand];
    # Second of three loops. Check to see if this line has already been
    # used.
    while ($used[$rand]) {
        # Initialize these variables here so that our third loop will
        # work. The random number should be less than the total number
        # of lines, because one of our lines is 0.
        $rand = $#lines + 1;
        $oldrand = $rand;
        # Third of three loops. Check to be certain that we didn't get
        # a random number that exceeds our array.
        while ($rand eq $oldrand) {
            # Make a random integer
            $rand = rand($oldrand);
            $rand = int($rand);
        }
        # Read our line from the array into our variable.
        $lineread = $lines[$rand];
    }
    # Print our line. Very important.
    print "$lineread\n";
    # Mark the line as used.
    $used[$rand] = 1;
    # Count it.
    $secondcount++;
}