Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^4: Using map function to print few elements of list returned by sort function

by jaypal (Beadle)
on May 26, 2014 at 00:28 UTC ( [id://1087382]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Using map function to print few elements of list returned by sort function
in thread Using map function to print few elements of list returned by sort function

With your hint, I was able to do the following

perl -F':' -lane ' push @{$h{$F[1]}}, [$F[0],$_] }{ print $_->[1] for map { splice [sort {$b->[0] <=> $a->[0]} @{$h{$_}}], +0,4 } keys %h' file 20470:ZM:Samfya:Africa 20149:ZM:Sesheke:Africa 18638:ZM:Siavonga:Africa 699385:ZW:Bulawayo:Africa 61739:ZW:Chinhoyi:Africa 47294:ZW:Chegutu:Africa 37423:ZW:Bindura:Africa

Thanks LanX, your guidance was much appreciated.

  • Comment on Re^4: Using map function to print few elements of list returned by sort function
  • Download Code

Replies are listed 'Best First'.
Re^5: Using map function to print few elements of list returned by sort function
by LanX (Saint) on May 26, 2014 at 11:24 UTC
    this can be simplified (and will work with older perl-versions)

    perl -F':' -lane ' push @{$h{$F[1]}}, [$F[0],$_] }{ print $_->[1] for map { ( sort {$b->[0] <=> $a->[0]} @$_ )[0..3] } val +ues %h' file 20470:ZM:Samfya:Africa 20149:ZM:Sesheke:Africa 18638:ZM:Siavonga:Africa 699385:ZW:Bulawayo:Africa 61739:ZW:Chinhoyi:Africa 47294:ZW:Chegutu:Africa 37423:ZW:Bindura:Africa

    Please note that countries with less than 4 cities will have empty lines.

    But I'd rather prefer chaining only maps...

    Cheers Rolf

    ( addicted to the Perl Programming Language)

    update

    to avoid empty lines skip the -l option

    perl -F':' -ane ' push @{$h{$F[1]}}, [$F[0],$_] }{ print $_->[1] for map { ( sort {$b->[0] <=> $a->[0]} @$_ )[0..3] } val +ues %h' file 20470:ZM:Samfya:Africa 20149:ZM:Sesheke:Africa 18638:ZM:Siavonga:Africa 699385:ZW:Bulawayo:Africa 61739:ZW:Chinhoyi:Africa 47294:ZW:Chegutu:Africa 37423:ZW:Bindura:Africa

    elaboration

    values instead of keys

    (List)[slice] instead of splice

    -l chomps and sets auto-newline in $\

      Thanks Rolf, using values instead of keys does make a lot sense. Thank you for sharing this. :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1087382]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-25 06:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found