Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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) {     ... } 
like image 366
kal Avatar asked Sep 17 '10 20:09

kal


People also ask

What is the value of an uninitialized variable in Perl?

Perl's “Use of uninitialized value” warning is a run-time warning encountered when a variable is used before initialization or outside its scope. The warning does not prevent code compilation.

How do I initialize a variable in Perl?

Initializing Variables in Perlmy $some_text = 'Hello there. '; # A number my $some_number = 123; # An array of strings. my @an_array = ('apple', 'orange', 'banana'); # An array of numbers. my @another_array = (0, 6.2, 9, 10); # A hash of week day indexes vs.

What is scalar variable in Perl?

A scalar is a variable that stores a single unit of data at a time. The data that will be stored by the scalar variable can be of the different type like string, character, floating point, a large group of strings or it can be a webpage and so on. Example : Perl.


1 Answers

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'; 
like image 74
rafl Avatar answered Oct 11 '22 16:10

rafl