compare versions.

Hi ,
I have versions something like 1.10.0 and 1.9.1 and i want to compare them.
I wrote sample program like below.

#!/usr/bin/perl
my $var1 = "1.10.0";
my $var2 = "1.9.0";
if ($var1 eq $var2)
{
print "EQUAL\n";
}
if ($var1 gt $var2)
{
print "GREATER $var1 $var2\n";
}
if ($var1 lt $var2)
{
print "LOWER $var1 $var2\n";
}

This is printing LOWER ene though 1.10.0 is greater than 1.9.1.
Please help me how to compare these type of numbers.

They look like strings to me. :smiley:

You may have to split them at the decimal and compare.

Since they're not pure numbers, Perl is treating them like strings, and then the comparison follows the rules of the strcmp function. The first and second character in both are the same, but the third is different, and 1 comes before 9, and is thus considered lower.

A ksh solution :

#!/usr/bin/ksh
# Usage: $0 version1 version2

set -o nounset

oIFS="$IFS" ;IFS='.'
set -A v1 $1
set -A v2 $2
IFS="${oIFS}"

cnt1=${#v1[*]}
cnt2=${#v2[*]}
(( cnt1 > cnt2 )) && cnt=$cnt1 || cnt=$cnt2;

i=0
result="EQUAL"
while (( i <= cnt ))
do
    (( n1 = ${v1[$i]-} + 0 ))
    (( n2 = ${v2[$i]-} + 0 ))
    if (( n1 > n2 ))
    then
        result="GREATER"
        break
    elif (( n1 < n2 ))
    then
        result="LOWER"
        break
    fi
    (( i += 1 ))
done

print ${result} $1 $2

Examples:

$ ./cmpv.ksh 1.2.3 1.2.3
EQUAL 1.2.3 1.2.3
$ ./cmpv.ksh 1.2.4 1.2.3
GREATER 1.2.4 1.2.3
$ ./cmpv.ksh 1.2.4 1.2.4.1
LOWER 1.2.4 1.2.4.1

Jean-Pierre.