Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Best 20 after sort

by seaver (Pilgrim)
on Oct 20, 2008 at 14:15 UTC ( [id://718232]=perlquestion: print w/replies, xml ) Need Help??

seaver has asked for the wisdom of the Perl Monks concerning the following question:

Dear all,

A simple question that I couldn't seem to find the answer for, perhaps because I wasn't sure how to frame it in English.
foreach my $g(sort {$Averages{$a} <=> $Averages{$b}} keys %Averages){ print $g,"\t",$Averages{$g},"\n"; }
If I just wanted the best 20, is it possible to do this in the same line as the sort?
Thanks
Sam

Replies are listed 'Best First'.
Re: Best 20 after sort
by Taulmarill (Deacon) on Oct 20, 2008 at 14:24 UTC
    Yes, like this:
    foreach my $g( (sort {$Averages{$a} <=> $Averages{$b}} keys %Averages) +[0..19] ){ print $g,"\t",$Averages{$g},"\n"; }

    The parenthesis surrounding the sort turn the return value into a list which can be sliced like an array.
Re: Best 20 after sort
by Limbic~Region (Chancellor) on Oct 20, 2008 at 14:23 UTC
      L~R
      I was using last, but I knew there'd be a more concise way of doing it.
      S
Re: Best 20 after sort
by salva (Canon) on Oct 21, 2008 at 07:51 UTC
    You can use Sort::Key::Top, in particular if you want to extract the top 20 for a large array:
    use Sort::Key::Top qw(nkeytopsort); my @top20 = nkeytopsort { $Averages{$_} } 20 => keys %Averages;
Re: Best 20 after sort
by GrandFather (Saint) on Oct 20, 2008 at 20:08 UTC
    say join ("\n", map {"$_,\t$Averages{$_}"} (sort {$Averages{$a} <=> $A +verages{$b}} keys %Averages)[0..19]);

    Perl reduces RSI - it saves typing
Re: Best 20 after sort
by johngg (Canon) on Oct 20, 2008 at 18:15 UTC
    In the spirit of TIMTOWTDI, a different approach using sort, grep and map in a do block.

    use strict; use warnings; my %Ave = map { $_ => rand } q{a} .. q{z}; print do { my $count = 0; map { qq{$_\t$Ave{ $_ }\n} } grep { $count ++ < 20 } sort { $Ave{ $a } <=> $Ave{ $b } } keys %Ave; };

    I hope this is of interest.

    Cheers,

    JohnGG

Log In?
Username:
Password:

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

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

    No recent polls found