How to check if a scalar variable is defined in Perl?
Question
How to check if a scalar variable is defined in Perl?
In Perl, checking if a scalar variable is defined is a common task, especially to distinguish between an undefined value and one that is set but possibly empty or zero. The built-in function defined is specifically designed to determine whether a scalar variable has a defined (non-undefined) value.
What Does defined Mean?
A scalar variable in Perl can have several states:
undef: The variable has no value assigned, or has been explicitly undefined.- Defined but False-like: Values such as
0,''(empty string), or'0', which are defined but evaluate to false in boolean context. - Defined and True: Non-empty strings, non-zero numbers, references, etc.
The defined function returns true if the variable is not undef, regardless of its truthiness.
Basic Usage
Here is an example demonstrating how to use defined to test a scalar variable:
#!/usr/bin/perl
use strict;
use warnings;
my $var;
if (defined $var) {
print "Variable is defined\n";
} else {
print "Variable is NOT defined\n";
}
$var = 0;
print "Now var is assigned 0.\n";
print "Defined? ", (defined $var ? "Yes" : "No"), "\n";
$var = '';
print "Now var is assigned empty string.\n";
print "Defined? ", (defined $var ? "Yes" : "No"), "\n";
$var = undef;
print "Now var is explicitly undefined again.\n";
print "Defined? ", (defined $var ? "Yes" : "No"), "\n";
Explanation
- When
$varis declared but not initialized, it isundefby default. - Assigning
0or''(empty string) makes the variable defined, though they are false in boolean context. - Explicitly assigning
undefmakes it undefined again.
Common Pitfalls
- Checking
if ($var)is not the same asif (defined $var), because false values like0or''will fail anif ($var)test even if they are defined. - Using uninitialized values (undefined scalars) in operations often results in warnings if
use warningsis enabled.
Version Notes
The defined function works the same across Perl 5 versions and is fundamental Perl syntax. No changes from early Perl 5 versions to recent ones affect its behavior substantially.
In summary, always use defined to check if a scalar has an assigned value distinct from undef. This avoids bugs related to using uninitialized variables.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 8ms
Variable is NOT defined
Now var is assigned 0.
Defined? Yes
Now var is assigned empty string.
Defined? Yes
Now var is explicitly undefined again.
Defined? No
(empty)