Perl | defined() Function
Last Updated :
21 Feb, 2019
Defined() in Perl returns true if the provided variable ‘VAR’ has a value other than the undef value, or it checks the value of $_ if VAR is not specified. This can be used with many functions to detect for the failure of operation since they return undef if there was a problem.
If VAR is a function or reference of a function, then it returns true if the function has been defined else it will return false if the function doesn’t exist. If a hash element is specified, it returns true if the corresponding value has been defined, but it doesn’t check for the existence of the key in the hash
Syntax: defined(VAR)
Parameters:
VAR which is to be checked
Returns:
Returns 0 if VAR is undef and 1 if VAR contains a value
Example 1:
$X = "X is defined" ;
if ( defined ( $X ))
{
print "$X\n" ;
}
if ( defined ( $Y ))
{
print "Y is also defined\n" ;
}
else
{
print "Y is not defined\n" ;
}
|
Output:
X is defined
Y is not defined
Example 2:
sub X
{
$VAR = 20;
}
if ( defined (X))
{
print "Function Exists\n" ;
}
if ( defined ( $Y ))
{
print "Y is also defined\n" ;
}
else
{
print "Y is not defined\n" ;
}
|
Output:
Function Exists
Y is not defined
Share your thoughts in the comments
Please Login to comment...