NerdVana

There are 10 types of people: those who speak binary, and those who don't.

Version sorting in Perl

Written by Eric Schwimmer

Need to sort two or more numeric version strings in Perl? Hate life? Then consider using this little beaut:

sub verComp                                                    
{                                                              
    my ($a,$b) = map [split '\.'], @_;                         
    for (0..($#$a,$#$b)[$#$a>$#$b])                            
      { return $a->[$_] <=> $b->[$_] if $a->[$_] <=> $b->[$_] }
    return $#$a <=> $#$b;                                      
}                                                              

my @versions = ('1.2.3.4','1.2.3','3.2.3','1.2.3.4.5','2.3.4');
print join ' -> ', sort { verComp($a,$b) } @versions;          

It works!

$ ./vercomp.pl
1.2.3 -> 1.2.3.4 -> 1.2.3.4.5 -> 2.3.4 -> 3.2.3


comments powered by Disqus