snoofkin snoofkin - 1 year ago 59
Perl Question

Perl compare operators and stringified "numbers"

I've been working a lot lately with perl, still I dont really know how

<,>,>=,=<, ne,gt
, etc.. on stringified "numbers", by "number" I mean something like: ''

correct me If I'm wrong, the following returns true:

if ('1.4.5' > '8.7.8');

because both will be coerced to true (not an empty string).
but, how does
,etc string operators work on such numbers?

basically I'm trying to compare version numbers consisted of the following form:

I can make a numerical comparison of each digit, but before, I ranther want to know of the
string comparing operators perform on such strings.


Answer Source

First: Please use warnings all the time. You would have realized the following at once:

$ perl -wle 'print 1 unless "1.4.5" > "8.7.8"'
Argument "8.7.8" isn't numeric in numeric gt (>) at -e line 1.
Argument "1.4.5" isn't numeric in numeric gt (>) at -e line 1.

Perl v5.9.0 came distributed with version. And this module makes it very easy to compare version numbers:

use warnings;
use version;

my ($small, $large) =  (version->parse('1.4.5'), version->parse('8.7.8'));

print "larger\n"    if $small > $large;
print "smaller\n"   if $small < $large;