Perl | defined() Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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";
}

chevron_right


Output:

X is defined
Y is not defined

 
Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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";
}

chevron_right


Output:

Function Exists
Y is not defined


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.