NerdVana

F u cn rd ths, u cn gt a gd jb n cmptr prgrmmng.

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