· Offer Kaye > Perl > Print File Randomly

Explanation of 'Print File Randomly' Perl oneliner

Here is the code again: perl -e'@l=<>;@l[$i,$s]=@l[$s=rand$i,$i]while++$i<@l;print@l'
"@l=<>" - slurp in the entire input file into the array @l.
"while++$i<@l" - foreach input line, increment $i by 1 (starts at 0) and do the code behind the while
"@l[$i,$s]=@l[$s=rand$i,$i]" - "@l[x,y]=@l[y,x]" is a "hash slice", i.e. it swaps $l[x] with $l[y]. In this case, $s first gets the value of rand of $i, then the swap is made. Thus, for each line of input, there is some chance for it to be swapped with a random previous line. Note that $s get implicitly floored to an int before being used as an array subscript.
"print@l" - print the file with the shuffled lines back to STDOUT.

Usage Example

Given an input file called "example" with the contents:
a
b
c
d

Then running the following from the command line:
perl -e'@l=<>;@l[$i,$s]=@l[$s=rand$i,$i]while++$i<@l;print@l' example
will print to STDOUT the four lines of "example", but in random order.

Offer Kaye / To contact me, email me at: offer.kaye no spam at gmail dot com / Last Modified: Thu Jul 15 23:04:09 2004

Valid XHTML 1.0! Valid CSS!