Monday, September 13, 2010

Operators in perl - relational operators

Note eq is for string and == is for integers. So here are operator for int and corresponding operator for strings.


Comparison Numeric String
Equal == eq
Not equal != ne
Greater than > gt
Less than < lt
Greater than or equal to >= ge
Less than or equal to <= le

Logical operators
 &&,and
||      or

Logical expression
The next few structures rely on a test being true or false. In Perl any non-zero number and non-empty string is counted as true. The number zero, zero by itself in a string, and the empty string are counted as false. Here are some tests on numbers and strings.

$a == $b                # Is $a numerically equal to $b?
# Beware: Don't use the = operator.
$a != $b # Is $a numerically unequal to $b?
$a eq $b # Is $a string-equal to $b?
$a ne $b # Is $a string-unequal to $b?


You can also use logical and, or and not:

($a && $b)              # Is $a and $b true?
($a || $b) # Is either $a or $b true?
!($a) # is $a false?

Note that perl is loosely typed language and allows you anything..which you do with
int etc to do with strings. So here is one eg.
So far we have been testing numbers, but there is more to life than numbers. There are strings too, and these need testing too.
$name  = 'Mark';

$goodguy = 'Tony';

if ($name == $goodguy) {
print "Hello, Sir.\n";
} else {
print "Begone, evil peon!\n";
}
Something seems to have gone wrong here. Obviously Mark is different to Tony, so why does perl consider them equal?
Mark and Tony are equal -- numerically. We should be testing them as strings, not as numbers. To do this, simply substitute == for eq and everything will work as expected.

No comments:

Post a Comment