1. Perl
  2. builtin functions
  3. here

undef function - undefined value

You can use the undef function to set a undefined value . Alternatively, undefine the value of the variable specified in the argument.

undef
undef(variable)

Set the undefined value as follows. The value of the variable "$name" becomes undefined.

$name = "Kimoto";
$name = undef;

You can also undefine the value of a variable by passing the variable as an argument of the undef function as follows.

$name = "Kimoto";
undef $name;

You can also use the undef function for arrays and hashes.

@names = undef;
undef @names;

%scores = undef;
undef %score;

Judgment of undefined value

You can use defined function to determine if it is an undefined value. Returns true if defined, false if undefined.

if (defined $name) {
  ...
}

It's also a good idea to write using unless to handle cases where the value is undefined.

unless (defined $name) {
  # What to do if undefined
}

Comparison with undefined value

undef is treated as an "empty string" when compared as a string and as "0" when compared as a number.

undef == 0
undef eq ""

If you use warnings module, it will warn you in such a case and prevent bugs, so be sure to declare it.

use warnings;

Memory release using undef

Assigning undef frees the memory.

However, in Perl, a lexical variable automatically free memory at the end of scope, so you're unlikely to have a chance to use undef to free memory.

{
  my $num = 5;
}
# At the end of scope, "$num" memory is freed

However, even after the scope ends, the memory may not be released due to closures. In such cases, you can explicitly use undef to free memory.

Please refer to the following articles for closures.

Example

This is an example undef function that you can run and try.

use strict;
use warnings;

# Set undefined value for variable
my $name = "Kimoto";
$name = undef;

if (defined $name) {
  print "Defined";
}
else {
  print "Undef";
}

Related Informatrion