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

Hi guys,

I've been working on a sort function to sort a number
of version numbers, and...out of curiousity:
Is there a faster way to do it than this ?:
#!/usr/bin/perl -w use strict; sub ByVersion; my @VersionList=("1.1","1.1.1","2.0","1.2_patch3","33.0","1.1.1.1","1. +a.1","1.b.1","1.b.1.a","1.b.1.b","1.33.0","1.0.a","1.0.b","33.1","6.6 +.6","10.0","9.0","3.1.4","3.1.12"); chomp (@VersionList); my @Sorted=sort ByVersion @VersionList; print "Sorted to: @Sorted\n"; sub ByVersion { my @First=split /\./,$a; my @Second=split /\./,$b; my $Nr=($#First>$#Second)?$#Second:$#First; foreach(0..$Nr) { next if ($First[$_] eq $Second[$_]); return ("$First[$_]$Second[$_]"=~/^\d$/o)?($First[$_] <=> $Second[$_ +]):($First[$_] cmp $Second[$_]); } return ($#First>$#Second)?1:-1; }
Now the output is really what I would like it to be....
BUT... is there a quicker or more elegant way to do it ? ;))

I had my fun with it so far ;))), just wondering if there
are better ideas out there ;))

GrtZ!,

Replies are listed 'Best First'.
Re: Sort ByVersion
by japhy (Canon) on Nov 02, 2000 at 18:27 UTC
    There's a CPAN module for that already. ;) Take a look at Sort::Versions. It's not been touched in 4 years, so maybe someone can find something to optimize in it.

    And in general terms, you're better off using a transform of some kind... probably a schwartzian transform. And looking at the code, he could use it, too. Here's the skeleton:
    @sorted = map { $_->{ORIG_DATA} } sort { $a->{SORT_DATA} cmp $b->{SORT_DATA} } map { { ORIG_DATA => $_, SORT_DATA => func($_) } @original;


    $_="goto+F.print+chop;\n=yhpaj";F1:eval
      I just checked out the CPAN Module....

      <EGO MODE> I like mine better </EGO MODE>

      ;)))), really ;))
(tye)Re: Sort ByVersion
by tye (Sage) on Nov 02, 2000 at 21:05 UTC