Tuesday, April 9, 2019

Perl: compare strings with numbers


Usually we should not compare strings with  numbers. In perl, numbers are compared with <, >, <=, >=, == and !=; while strings are compared with lt, gt, le, ge, eq and ne. However, here are the comparison results just for curiosity:

my $str = "Hello";

print "str: $str \n";
if ($str > 0) {
    print "str > 0 \n";
} elsif ($str < 0) {
    print "str < 0 \n";
} else {
    print "str == 0 \n";
}

print "\n";

$str = "1Hello";

print "str: $str \n";
if ($str > 0) {
    print "str > 0 \n";
} elsif ($str < 0) {
    print "str < 0 \n";
} else {
    print "str == 0 \n";
}

print "\n";

if ("World" > 0) {
    print "World > 0 \n";
} elsif ("World" < 0) {
    print "World < 0 \n";
} else {
    print "World == 0 \n";
}

print "\n";

if ("World" gt 0) {
    print "World gt 0 \n";
} elsif ("World" lt 0) {
    print "World lt 0 \n";
} else {
    print "World == 0 \n";
}


The output of the above code is:
str: Hello 
str == 0 

str: 1Hello 
str > 0 

World == 0 

World gt 0 

No comments:

 
Get This <