kal kal - 2 months ago 7
Perl Question

How do I check if a Perl scalar variable has been initialized?

Is the following the best way to check if a scalar variable is initialized in Perl, using

defined
?

my $var;

if (cond) {
$var = "string1";
}

# Is this the correct way?
if (defined $var) {
...
}

Answer

Perl doesn't offer a way to check whether or not a variable has been initialized.

However, scalar variables that haven't been explicitly initialized with some value happen to have the value of undef by default. You are right about defined being the right way to check whether or not a variable has a value of undef.

There's several other ways tho. If you want to assign to the variable if it's undef, which your example code seems to indicate, you could, for example, use perl's defined-or operator:

$var //= 'a default value';
Comments