Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

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:




#!/usr/bin/perl
  
# Defining a variable
$X = "X is defined";
  
# Checking for existence of $X 
# with defined() function
if(defined($X)) 
{
    print "$X\n";
}
  
# Checking for existence of $Y 
# with defined() function
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:




#!/usr/bin/perl
  
# Defining a function
sub X
{
      
    # Defining a variable
    $VAR = 20;
}
  
# Checking for existence of $X 
# with defined() function
if(defined(X)) 
{
    print "Function Exists\n";
}
  
# Checking for existence of $Y 
# with defined() function
if(defined($Y)) 
{
    print "Y is also defined\n";
else
{
    print "Y is not defined\n";
}

Output:

Function Exists
Y is not defined



My Personal Notes arrow_drop_up
Recommended Articles
Page :