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:
Perl
my $x ;
print "The value of x is = ${x}" ;
|
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.
Perl
$k = 10;
print "The value of variable k is ${k}\n" ;
undef $k ;
print "The value of variable k is ${x}\n" ;
$m = 20;
print "The value of variable m is ${m}\n" ;
$m = undef ();
print "The value of variable m is ${m}\n" ;
|
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.
defined $variable_name
Perl
$k = 15;
if ( defined $k )
{
print "k is defined\n" ;
}
else
{
print "k is not defined\n" ;
}
$k = undef ;
if ( defined $k )
{
print "k is defined\n" ;
}
else
{
print "k is not defined\n" ;
}
|
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 “”.
Perl
$x = 125;
my $y ;
$z = $x + $y ;
print "The sum of x and y is ${z}\n" ;
$strx = "GFG" ;
my $stry ;
$strz = $strx . $stry ;
print "After concatenation of strx and stry ${strz}\n" ;
|
The sum of x and y is 125
After concatenation of strx and stry GFG
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
14 May, 2021
Like Article
Save Article