While I agree with boftx that a real script would be more appropriate for something like this in a production setting, I appreciate that pushing one-liners to their limits can make for good learning exercises.

As for your splice based solution, I think that's actually pretty good. Here are two small suggestions to tweak it further:

  1. You can get rid of the  BEGIN { $"=":" }  by using  $_  instead of  "@F"  to refer to the original line.

  2. You can get rid of the separate  %line  hash by adding that information directly to  %h  whose contents would then look like:
    ( ZM => [ [20470, "20470:ZM:Samfya:Africa"], [20149, "20149:ZM:Sesheke:Africa"], [18638, "18638:ZM:Siavonga:Africa"] ], ZW => [ ... ], ... )

Here's the one-liner with those changes, in a "scriptified" representation (which I find easier to work with; it's trivial to convert it back to the one-liner format by removing the lines with comments after them):

use warnings; # just for debugging use strict; # just for debugging my (%h, $k, @F); # just for debugging while (<>) { # -n chomp; # -l $\ = "\n"; # -l @F = split(':'); # -F":" -a push @{$h{ $F[1] }}, [$F[0], $_]; } for $k (sort keys %h) { print $_->[1] for splice [sort {$b->[0]<=>$a->[0]} @{$h{$k}}], 0, 4 } # -n

In reply to Re: Using map function to print few elements of list returned by sort function by smls
in thread Using map function to print few elements of list returned by sort function by jaypal

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.