Tuesday, June 21, 2011

perl check true or false

In perl  0 and "" are considered as false and all others are considered as true.

In Perl for checking the variable  is assigned , you should not check the value returned is false,as it may fail in some cases.

Consider for example:

if ($variable)
{
          print "valuse present";
}
else
{
         print "value not present"
}

This check will fail tremendously when $variable is equal to 0


The correct way to do it is


while (defined ($variable)){
          print "valuse present";
}
else
{
         print "value not present"
}

In case of hash to check if the element is present in the hash.

In this case the exists operator has to be used.


if (exists($hash{'foo'})) {      }   TRUE

In this case if you use defined function it will always return true.

perl true false

In perl  0 and "" are considered as false and all others are considered as true.

In Perl for checking the variable  is assigned , you should not check the value returned is false,as it may fail in some cases.

Consider for example:

if ($variable)
{
          print "valuse present";
}
else
{
         print "value not present"
}

This check will fail tremendously when $variable is equal to 0


The correct way to do it is


while (defined ($variable)){
          print "valuse present";
}
else
{
         print "value not present"
}

In case of hash to check if the element is present in the hash.

In this case the exists operator has to be used.


if (exists($hash{'foo'})) {      }   TRUE

In this case if you use defined function it will always return true.

Comparison in perl

Perl has two different set of comparison operators for both numbers and string.

For string we need to use only the following operators
In case of string the comparison takes place ASCIIbetically -that is by comparing ASCII values of the characters in Strings.


'a' lt 'b'         TRUE
'a' eq 'A'      FALSE-capitalization
"joseph" eq "joseph "  FALSE-spaces count
"H"  cmp "He"  -1--cmp operator

The cmp operator does a string comparison and returns -1,0,1 depending on the left argument is greater than,less than the right argument.
This operator should not be used for string comparison


"aaaaaaaa"  == "fgdfgdfgdf"    TRUE always as for equal to operator the string always looks to be 0

Numeric comparison use the following:

0<5                     TRUE
10 == 10.0          TRUE
10 <=> 9.5          1     --->spaceship operator
The spaceship operator is like cmp for strings except it compares numerically.
Should not use string comparators for numeric.

'10' gt '2'               FALSE -  '1' sorts before 2
"10.0" eq "10"       FALSE-different strings