· Offer Kaye > Perl > Print Random Line
Explanation of 'Print Random Line' Perl oneliner
Here is the code again: perl -e'rand$.<1and$q=$_ while<>;print$q'
"while<>" - foreach input line
"rand$.<1" - if rand() of $. (the current line number) is less than 1
"and" - the right side will only be avaluated if the left side is true
"$q=$_" - then set $q to be equal to the current line
"print$q" - print the last line saved to $q 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'rand$.<1and$q=$_ while<>;print$q' example
will print to STDOUT one of the four letters a,b,c or d, randomly.
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