Here's an implementation of "Keep an array of the current top 20 ..." (as suggested by GrandFather):

my @top; while (<DATA>) { my ($id, $score) = split ' '; my $e = $top[-1]; # last/lowest entry in @top if ( !defined($e) || $score > $e->[1] ) { push @top, [$id, $score]; @top = sort {$b->[1] <=> $a->[1]} @top; pop @top if @top > 20; } } for (@top) { say "$_->[0] : $_->[1]"; } __DATA__ ID1 25 ID2 8 ID3 3 ... 42

(where the __DATA__ is just to indicate the format — you'd of course read from your huge file instead)

Update: actually, this wouldn't work ;( — e.g. if you encounter the largest value first   So, here's a corrected version (unfortunately less performant, because @top now is sorted for every iteration):

my @top; while (<DATA>) { my ($id, $score) = split ' '; push @top, [$id, $score]; @top = sort {$b->[1] <=> $a->[1]} @top; pop @top if @top > 20; }

(A quick test shows that on my somewhat aged hardware, this takes 280s for a 30_000_000 line file with random 8-digit scores — as opposed to 52s for the previous only-sometimes-correct version (40s of which are for mere reading/splitting).   This is still significantly faster, though, than reading the entire data into a hash and sorting that hash. I couldn't test the full 3e+07 lines (as I only have 4G of physical RAM), but a 3e+06 entry hash already took 220s (and 805M memory), and sorting doesn't scale linearly with size.)


In reply to Re: Dealing with Hash Table by Eliya
in thread Dealing with Hash Table by &#350;uRvīv&#337;r

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.