With warnings enabled, perl usually prints Use of uninitialized value $foo if $foo is used in an expression and hasn’t been assigned a value, but in some cases it’s OK, and the variable is treated as false, 0, or '' without a warning.
What are the cases where an uninitialized/undefined variable can be used without a warning?
Summary
Boolean tests
According to the perlsyn documentation,
Because the undefined value is false, the following program
outputs
DthroughGwith no warnings.Incrementing or decrementing an undefined value
There’s no need to explicitly initialize a scalar to zero if your code will increment or decrement it at least once:
The code above outputs
3with no warnings.Appending to an undefined value
Similar to the implicit zero, there’s no need to explicitly initialize scalars to the empty string if you’ll append to it at least once:
Autovivification
One example is “autovivification.” From the Wikipedia article:
For example:
Even though we don’t explicitly initialize the intermediate keys, Perl takes care of the scaffolding:
$VAR1 = { 'bar' => { 'baz' => { 'quux' => '1' } } };Without autovivification, the code would require more boilerplate:
Don’t confuse autovivification with the undefined values it can produce. For example with
we get
Use of uninitialized value in print at ./prog.pl line 6. $VAR1 = { 'bar' => { 'baz' => {} } };Notice that the intermediate keys autovivified.
Other examples of autovivification:
reference to array
reference to scalar
reference to hash
Sadly, Perl does not (yet!) autovivify the following:
Other mutators
In an answer to a similar question, ysth reports
Being “defined-or,”
//=happily mutates an undefined value without warning.