VOOZH about

URL: https://www.geeksforgeeks.org/perl/perl-undef-and-the-defined-function/

⇱ Perl | undef and the defined function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Perl | undef and the defined function

Last Updated : 11 Jul, 2025

undef is used for those variables which do not have any assigned value. One can compare it with NULL(in Java, PHP etc.) and Nil(in Ruby). So basically when the programmer will declare a scalar variable and don't assign a value to it then variable is supposed to be contain undef value. In Perl, if the initial value of a variable is undef then it will print nothing.
Example: 
 

Output: 
 

The value of x is = 


undef() function: undef is used to reset the value of any variable. It can be used with or without the parentheses. It means that parentheses are optional while using this function.
 

  • Example:
     

  • Output: 
     
The value of variable k is 10
The value of variable k is 
The value of variable m is 20
The value of variable m is 


defined() function: This function is used to check whether a value is assigned to the variable or not. It will return True if the value is assigned to the variable otherwise it will return false. 
 

  • Syntax: 
     
defined $variable_name
  • Example:
     

  • Output: 
     
k is defined
k is not defined


Note: Although undefined variables have no defined value, but they can take null value during the operation. For example, if user is adding two variables x and y in which x is 5 and y is undefined, then the result would remain 5 because y will take up the value 0. Similarly, if user concatenates two strings strx and stry with strx as value "GGF" and stry is undef, the result would be "GFG", as stry takes the value of a blank string "".
 

  • Example: 
     

  • Output: 
     
The sum of x and y is 125
After concatenation of strx and stry GFG


 

Comment
Article Tags:
Article Tags:

Explore