Sort::Key::Natural - fast natural sorting
use Sort::Key::Natural qw(natsort); my @data = qw(foo1 foo23 foo6 bar12 bar1 foo bar2 bar-45 foomatic b-a-r-45); my @sorted = natsort @data; print "@sorted\n"; # prints: # b-a-r-45 bar1 bar2 bar12 bar-45 foo foo1 foo6 foo23 foomatic use Sort::Key::Natural qw(natkeysort); my @objects = (...); my @sorted = natkeysort { $_->get_id } @objects;
This module extends the Sort::Key family of modules to support natural sorting.
Under natural sorting, strings are splitted at word and number boundaries, and the resulting substrings are compared as follows:
numeric substrings are compared numerically
alphabetic substrings are compared lexically
numeric substrings come always before alphabetic substrings
Spaces, symbols and non-printable characters are only considered for splitting the string into its parts but not for sorting. For instance foo-bar-42 is broken in three substrings foo, bar and 42 and after that the dashes are ignored.
foo-bar-42
foo
bar
42
Also, once this module is loaded, the new type natural (or nat) will be available from Sort::Key::Maker. For instance:
natural
nat
use Sort::Key::Natural; use Sort::Key::Maker i_rnat_keysort => qw(integer -natural);
creates a multikey sorter i_rnat_keysort accepting two keys, the first to be compared as an integer and the second in natural descending order.
i_rnat_keysort
the functions that can be imported from this module are:
returns the elements of @data sorted in natural order.
@data
returns the elements of @data sorted in natural descending order.
returns the elements on @array naturally sorted by the keys resulting from applying them CALC_KEY.
@array
CALC_KEY
is similar to natkeysort but sorts the elements in descending order.
natkeysort
these functions are similar respectively to natsort, rnatsort, natsortkey and rnatsortkey, but they sort the array @data in place.
natsort
rnatsort
natsortkey
rnatsortkey
transforms key $key in a way that when sorted with Sort::Key keysort results in a natural sort. If the argument $key is not provided it defaults to $_
$key
$_
Sort::Key, Sort::Key::Maker.
Other module providing similar functionality is Sort::Naturally.
Copyright (C) 2006 by Salvador Fandiño, <sfandino@yahoo.com>.
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.4 or, at your option, any later version of Perl 5 you may have available.
To install Sort::Key, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sort::Key
CPAN shell
perl -MCPAN -e shell install Sort::Key
For more information on module installation, please visit the detailed CPAN module installation guide.