FIX: Suppress Perl "uninitialized value" warnings (strongish medicine for clueful users only)

If you have written any Perl of moderate complexity, and especially if your Perl of moderate complexity has included CGI and Database interactions, (or any time you have to deal with undef or NULL vs. a blank string, and you might have either of the two), you have run across warnings like this (maybe to STDERR, or maybe in your /etc/httpd/logs/error_log):

Use of uninitialized value in concatenation (.) or string at ...

Use of uninitialized value in numeric gt (>) at ...

etc.  How can you stop these error messages (warnings, really) from blocking up your logs and your STDERR?

In fact, you should be somewhat concerned at your uninitialized value warnings.  After all, they are there for a reason.  A really good piece of code ought not to generate them, at least in theory.  However, sometimes you want the benefit of use strict and -w warnings, and you have at once good reason not to want to know about uninitialized values.  What might these be?

  • You are doing string interpolation into something where undef and "" are equivalent for your purposes (most web page work)
  • You are doing some conditionals or string comparisons based upon data that come in from one crufty source or another, like CGI, and you don't want to make a separate case for undef and "".
  • Relative quick-and-dirtiness where you want at least use strict in order to prevent egregious code but you don't need to hear about the semantic difference between undefined and the emtpy string.

In these cases, if you are using Perl 5.6+, you are in luck.  You can carefully wrap the specific section of code that has a good reason for not caring about undef values in a block (curly braces) and write:

  no warnings 'uninitialized';
  if ( CGI::param('name') ) {
    print "Hello, " . CGI::param('name');
  else {
    print "Hi there.";

Leave a Reply