I thought of doing something similar with an array, but decided the memory cost was too high. That was a guess, but even your much more compact idea of a packed string will occupy 40MB for a ten-million line data file. That's not necessarily prohibitive, but it might be so on a busy machine.

Here's a short bit to write the packed offsets to a file:

#!/usr/bin/perl open my $out, '>:raw', '/path/to/data.offsets' or die $!; open my $in, '<', '/path/to/data.dat' or die $!; my $offset = 0; local ($_,$\); my ($this, $last) = 0; while (<$in>) { ($last, $this) = ($this, tell $in); print $out pack 'i', $last; } close $in or warn $!; close $out or warn $!;
That file can be read and used like this:
my $index = do { local $/; open my $idx, '<:raw', '/path/to/data.offsets' or die $!; <$idx> }; open my $dat, '<', '/path/to/data.dat' or die $!; my ($offset) = unpack 'i', substr $index, 4*rand(length($index)/4), 4; seek $dat, $offset, 0 or warn $!; print scalar <$dat> or warn $!; close $dat or warn $!; close $idx or warn;

After Compline,
Zaxo


In reply to Re^3: Approach to efficiently choose a random line from a large file by Zaxo
in thread Approach to efficiently choose a random line from a large file by Your Mother

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.