Dear Monks,

I tried to randomly select 20 million lines from a 40 million lines file.

I have two questions.

First, how to select the 20 million lines from the file without bias. I have tried to use perl. But it seems perl is not that good for such thing, so I used R to generate 20 million index to create an index file (rand_sorted.txt) and use it to print the selected lines.

Second, my code is as below:

#!/usr/bin/perl -w use strict; open RND, "rand_sorted.txt" or die "no file found"; my @rnd; @rnd = grep {chomp;} <RND>; close RND; WILLOP: while (<>){ chomp; FORLOP: foreach my $i (@rnd){ if ($i != $rnd[$#rnd]){ if ($. == $i){ print "$_\n"; shift @rnd; last FORLOP; } else { print "$_\n"; last FORLOP; } }

This works fine and fast for me, but I just hate these two loops nested each other, it looks stupid, or maybe it's stupid. Any one can give me an idea how to do it? Thanks.


In reply to A series of random number and others by lightoverhead

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.