- COPYRIGHT AND LICENSE
- SEE ALSO
Sort::filevercmp - Sort version strings as in GNU filevercmp
use Sort::filevercmp; my @sorted = sort filevercmp 'foo-bar-1.2a.tar.gz', 'foo-bar-1.10.zip'; my $cmp = filevercmp 'a1b2c3.tar', 'a1b2c3.tar~'; say $cmp ? $cmp < 0 ? 'First name' : 'Second name' : 'Names are equal'; # Pre-parse list for faster sorting use Sort::filevercmp 'fileversort'; my @sorted = fileversort @filenames;
Perl implementation of the
filevercmp function from gnulib.
filevercmp is used by the sort(1) (
-V option) and ls(1) (
-v option) GNU coreutils commands for "natural" sorting of strings (usually filenames) containing mixed version numbers and filename suffixes.
my $cmp = filevercmp $string1, $string2; my @sorted = sort filevercmp @strings;
Takes two strings and returns -1 if the first string sorts first, 1 if the second string sorts first, or 0 if the strings sort equivalently. Can be passed to sort directly as a comparison function. Exported by default.
my @sorted = fileversort @strings;
The sort algorithm works roughly as follows:
Hidden files (strings beginning with
.) go next, and are sorted among themselves according to the remaining rules
Each string is split into sequences of non-digit characters and digit (
0-9) characters, ignoring any filename suffix as matched by the regex
/(?:\.[A-Za-z~][A-Za-z0-9~]*)*$/, unless the strings to be compared are equal with the suffixes removed.
The first non-digit sequence of the first string is compared lexically with that of the second string, with letters (
a-zA-Z) sorting first and other characters sorting after, ordered by character ordinals. The tilde (
~) character sorts before all other characters, even the end of the sequence. Continue if the non-digit sequences are lexically equal.
The first digit sequence of the first string is compared numerically with that of the second string, ignoring leading zeroes. Continue if the digit sequences are numerically equal.
Repeat steps 4 and 5 with the remaining sequences.
This sort algorithm ignores the current locale, and has unique rules for lexically sorting the non-digit components of the strings, designed for sorting filenames. There are better options for general version string sorting; see "SEE ALSO".
Report any issues on the public bugtracker.
Dan Book <email@example.com>
This software is Copyright (c) 2017 by Dan Book.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)
version - for comparing Perl version strings
Sort::Versions - for comparing standard version strings
Sort::Naturally - locale-sensitive natural sorting of mixed strings