Friday, June 5, 2009

If loop - numerical vs string comparison

Lets see the difference between numerical comparison and string comparison:

Simplest example of if-else loop


#!/usr/bin/perl

$a=9;
$b=35;

print "CASE 1: Following is using numerical comparison operator \n";
if ( $a > $b ) {
print "$a is greater than $b \n";
} else {
print "$a is less than $b \n";
}

print "\n\n";

print "CASE 2: Following is using string comparison operator \n";
if ( $a gt $b ) {
print "$a is greater than $b \n";
} else {
print "$a is less than $b \n";
}


The output is as shown below: (in one case 9 is smaller than 35 and in other case, opposite)

c:\>perl script3.pl
CASE 1: Following is using numerical comparison operator
9 is less than 35


CASE 2: Following is using string comparison operator
9 is greater than 35

No comments:

About Me

My photo
Unix geek with AWS, Cloud computing, Linux, Netapp, VMware, Scripting background! :)