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.