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.

No comments:

Post a Comment