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 checkedReturns:
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
Recommended Posts:
- Perl | undef and the defined function
- Perl | Basic Syntax of a Perl Program
- Perl Tutorial - Learn Perl With Examples
- Perl | split() Function
- Perl | chomp() Function
- Perl | chop() Function
- Perl | rename() Function
- Perl | cos() Function
- Perl | sin() Function
- Perl | abs() function
- Perl | atan2() Function
- Perl | splice() - The Versatile Function
- Perl | delete() Function
- Perl | each() Function
- Perl | index() Function
- Perl | int() function
- Perl | join() Function
- Perl | keys() Function
- Perl | lc() Function for Lower Case Conversion
- Perl | lcfirst() Function
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.

