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) {
...
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
undefby default. You are right aboutdefinedbeing the right way to check whether or not a variable has a value ofundef.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: