Sort::Key::Top - select and sort top n elements
use Sort::Key::Top (nkeytop top); # select 5 first numbers by absolute value: @top = nkeytop { abs $_ } 5 => 1, 2, 7, 5, 5, 1, 78, 0, -2, -8, 2; # ==> @top = (1, 2, 1, 0, -2) # select 5 first words by lexicographic order: @a = qw(cat fish bird leon penguin horse rat elephant squirrel dog); @top = top 5 => @a; # ==> @top = qw(cat fish bird elephant dog);
The functions available from this module select the top n elements from a list using several common orderings and custom key extraction procedures.
They are all variations around
keytopsort { CALC_KEY($_) } $n => @data;
This function calculates the ordering key for every element in @data using the expression inside the block. Then it selects and orders the $n elements with the lower keys when compared lexicographically.
@data
$n
It is equivalent to the pure Perl expression:
(sort { CALC_KEY($a) cmp CALC_KEY($b) } @data)[0 .. $n-1];
Variations allow to:
topsort 5 => qw(a b ab t uu g h aa aac); ==> a aa aac ab b
top 5 => qw(a b ab t uu g h aa aac); ==> a b ab aa aac
For instance comparing the keys as numbers, using the locale configuration or in reverse order:
rnkeytop { length $_ } 3 => qw(a ab aa aac b t uu g h); ==> ab aa aac rnkeytopsort { length $_ } 3 => qw(a ab aa aac b t uu g h); ==> aac ab aa
A prefix is used to indicate the required ordering:
lexicographical ascending order
lexicographical descending order
lexicographical ascending order obeying locale configuration
lexicographical descending order obeying locale configuration
numerical ascending order
numerical descending order
numerical ascending order but converting the keys to integers first
numerical descending order but converting the keys to integers first
numerical ascending order but converting the keys to unsigned integers first
numerical descending order but converting the keys to unsigned integers first
The full list of available functions is:
top ltop ntop itop utop rtop rltop rntop ritop rutop keytop lkeytop nkeytop ikeytop ukeytop rkeytop rlkeytop rnkeytop rikeytop rukeytop topsort ltopsort ntopsort itopsort utopsort rtopsort rltopsort rntopsort ritopsort rutopsort keytopsort lkeytopsort nkeytopsort ikeytopsort ukeytopsort rkeytopsort rlkeytopsort rnkeytopsort rikeytopsort rukeytopsort
Sort::Key, "sort" in perlfunc.
The Wikipedia article about selection algorithms http://en.wikipedia.org/wiki/Selection_algorithm.
Copyright (C) 2006 by Salvador Fandiño
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.8 or, at your option, any later version of Perl 5 you may have available.
To install Sort::Key::Top, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sort::Key::Top
CPAN shell
perl -MCPAN -e shell install Sort::Key::Top
For more information on module installation, please visit the detailed CPAN module installation guide.