checking version in perl

I am writing sub routine for checking version but some how I am not getting correct output if version 1 < version 2 then -1 if version 1 = version 2 then 0 if version1 > version 2 then 1 Not sure Why I am not getting correct result

sub checkVersion
    {
        my $var1 = shift;
        my $var2 = shift;
        my @var1_seg = split (/./, $var1);
        my @var2_seg = split (/./, $var2);
        for( my $i = 0; $i < @var1_seg; $i++ ) 
        {
            if( $var1_seg[$i] < $var2_seg[$i] ) 
            {
                 return -1;
            }
            elsif( $var1_seg[$i] > $var2_seg[$i] )
            {
                 return 1;
            }
         }

      return 0;
    }

Answers


On one note, you need to escape the dot . using split as it is considered a special character in regular expression. Instead, use the version module which makes it very easy to compare version numbers:

use strict;
use warnings;
use version;
use feature 'say';

say checkVersion('5.10.0', '5.14.0'); # Returns -1
say checkVersion('5.10.0', '5.10.0'); # Returns  0
say checkVersion('5.14.0', '5.10.0'); # Returns  1

sub checkVersion {
   my $var1 = shift;
   my $var2 = shift;
   return version->parse($var1) <=> version->parse($var2);
}

Use version Instead. This module is immensely helpful when you are dealing with versions.


Shouldn't this:

my @var1_seg = split (/./, $v1);
my @var2_seg = split (/./, $v2);

be this:

my @var1_seg = split (/./, $var1);
my @var2_seg = split (/./, $var2);

As a general comment, always 'use strict;' at the top of your programs to avoid problems like this.


Need Your Help

SQL Query Join & Date Manipulation

sql oracle join

I'm having trouble with a particular Oracle query. I'm trying to write a query to pull the following data.

Enumerate all open connections

c# .net sockets networking

Is it possible to enumerate all open connections of the current process using .NET? (similarly to the way the netstat tool does this)

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.