My Favorite Warnings: uninitialized

This warning was touched on in A Belated Introduction, but I thought it deserved its own entry.

When a Perl scalar comes into being, be it an actual scalar variable or an array or hash entry, its value is undef. Now, the results of operating on an undef value are perfectly well-defined: in a nuneric context it is 0, in a string context it is '', and in a Boolean context it is false.

The thing is, if you actually operate on such a value, did you mean to do it, or did you forget to initialize something, or initialize the wrong thing, or operate on the wrong thing? Because of the latter possibilities Perl will warn about such operations if the uninitialized warning is enabled.

If you really intended to do this, no warnings 'uninitialized'; will suppress the error.

Note that this warning has nothing to do with the fatal error Can't call method "%s" on an undefined value that turns up every so often on various Perl outlets. This generally results from an instantiator or other factory method returning undef on failure rather than throwing an exception, and the programmer not checking the value before using it. Because this error is fatal, it can not be turned off with the no warnings pragma.

Previous entries in this series:

  1. A Belated Introduction
  2. once
  3. redundant and missing
  4. exiting

Leave a comment

About Tom Wyant

user-pic Fine Perl code for over 0.005 centuries.