1. Perl
  2. builtin functions
  3. here

defined function - check if the value is defined

Use the defined function to see if the value is defined.

# Check if the value is defined
$is_defined = defined $value;

What is defined

What is the defined value that can be determined by the defined function? Let's think about it.

If a variable is declared, it will be undefined if initialization by assignment is not performed.

# Undefined immediately after declaration
my $value;

When you assign a value, the value is defined.

# Since the value is assigned, it will be in the defined state.
$value = 5;

If an undefined value is assigned using undef function, the value becomes undefined.

# Substituting undef makes it undefined
$value = undef;

What is the difference from the boolean value?

Note that the "defined/undefined" that can be determined by the defined function is different from the concept of "true/false". Defined means that it is not an undefined value.

True, on the other hand, is not a false value in Perl. Please refer to the following article for the boolean value.

What is the difference between "hash value defined" and "key exists"?

You can use exists function to check if the hash key exists. The existence of the key is different from the defined value.

The result of the judgment by the defined function and the judgment by the exists function may be different.

In the following cases, the value is undefined, but the hash key exists.

my %scores;

# Key exists, but value is undefined
$scores{math} = undef;

Define functions for arrays and hashes are deprecated

Arrays and hashes are not undefined values when declared, but are assigned an empty list.

my @nums;
my %scores;

This is the same as:

my @nums = ();
my %scores = ();

Its use for defined functions for arrays and hashes is deprecated. Instead, simply check if it's an empty list.

if (@nums) {...}
if (%scores) {...}

Convenient Defined - or operator

There is a convenient operator called Defined-or operator that allows you to assign the right-hand side if the value is undefined.

my $num;

# If undefined, substitute 3 using "defined-or operation"
$num //= 3;


This is an example to check if it is defined using the defined function.

use strict;
use warnings;

my $num = 3;

if (defined $num) {
  print "Defined\n";
else {
  print "Not defined\n";

It's also easy to read in combination with unless if undefined was the main logic.

use strict;
use warnings;

my $num;
unless (defined $num) {
  print "Not defined\n";

Related Informatrion