Wednesday, January 5, 2011

if and unless conditional statements in Perl

The following example finds the greatest number amongst three given numbers, 
finds the greater number between two given numbers and also checks for the 
equality of two string values

#!/usr/bin/perl

print "content-type: text/html \n\n"; 

$a=1;
$b=2;
$c=3;

if($a > $b && $a > c) # executes if the expression is true
{
 print "$a is greatest\n";
}
elsif($b > $a && $b > $c) # executes if the expression is true
{
 print "$b is greatest\n";
}
elsif($a == $b && $a == $c) # executes if the expression is true
{
 print "all are equal\n";
}
else
{
 print "$c is greatest\n";
}

unless ($b <= $a) # executes if the expression is false
{
 print "$b is greater than $a\n";
}

$string_1="your name";
$string_2="yours name";

if($string_1 eq $string_2) # executes if the expression is true
{
 print "both the strings are same\n"; 
}
else
{
 print "both the strings are not same\n"; 
}

Output:
-------
3 is greatest
2 is greater than 1
both the strings are not same

Numeric Comparison Operators:
-----------------------------
== equal to
!= not equal to
> greater than
< lesser than
>= greater or equal to
<= lesser or equal to

String/ Character Comparison Operators:
-----------------------------
eq => equal to
ne => not equal to
gt => greater than
lt => lesser than