in reply to reading a random line from a file

Just jump to a very random position via seek() and then read the next line you find:

open my $fh,'<',$some_file or die $!; my $size = -s $fh; seek $fh, rand($size) , 0; <$fh>; #throw away current line; my $randomline = <$fh>; close $fh;

Only problem is that you might seek() to a position in the last line of the file and will get no random line. But it's not too hard to solve this problem.

--
http://fruiture.de

Replies are listed 'Best First'.
Re: Re: reading a random line from a file
by sauoq (Abbot) on Nov 17, 2002 at 22:48 UTC

    Using seek for this is probably not a very good idea. Consider a file with these two lines:

    a bcdefghijklmnopqrstuvwxy z
    Most random seeks will end up in the second line. If you move backwards, you'll almost always pick the long line. If you move forwards, you'll almost always pick 'z'. One way or the other, your distribution isn't random at all but determined by line length.

    BrowserUk had the good sense to point out that the lines would have to be padded out to equal length to use this method.

    -sauoq
    "My two cents aren't worth a dime.";