++ed by:

1 PAUSE user

Dan Book


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;

Takes a list of strings and sorts them according to "filevercmp". The strings are pre-parsed so it may be more efficient than using "filevercmp" as a sort comparison function. Exported by request.


The sort algorithm works roughly as follows:

  1. Empty strings, ., and .. go first

  2. Hidden files (strings beginning with .) go next, and are sorted among themselves according to the remaining rules

  3. 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.

  4. 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.

  5. 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.

  6. 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 <dbook@cpan.org>


This software is Copyright (c) 2017 by Dan Book.

This is free software, licensed under:

  The Artistic License 2.0 (GPL Compatible)