Click to See Complete Forum and Search --> : Uninitialized variables


CyCo
04-07-2005, 11:38 AM
Below, you will find a rather trivial, although illustrative, example that I've put together to de-mystify my curiosity for finding out the truth of why this code (or any other code that involves uninitialized variables before runtime, for that matter) fails under use warnings FATAL => 'all'. I was under the impression that the code is both perfectly acceptable and programmatically correct, but it delivers these lines as warnings to the browser:

#Use of uninitialized value in string eq at line 13
#Use of uninitialized value in string eq at line 14

I understand what the warnings are and I know that they are minor, but my question is how does one go about using (use warnings FATAL => 'all') and rid the script of warnings, too? If the code is wrong, then what would be the proper usage? If it is a matter of acceptable code, but merely putting it inside of a block with warnings turned off, then that would be easy, although I don't think that is possible (unlike using strict). I guess I just want to find the truth of the matter. Whatever that may be. Anyone?


#!/usr/bin/perl

use strict;
use CGI ':standard';
use warnings FATAL => 'all';
use CGI::Carp 'fatalsToBrowser';

my($bkgcolor,$fntcolor);

print header, start_html('Uninitialized Variable Example');

foreach ('THIS IS ROW 1','THIS IS ROW 2','THIS IS ROW 3','THIS IS ROW 4') {
$bkgcolor = ($bkgcolor eq '#fff') ? '#f00' : '#fff';
$fntcolor = ($fntcolor eq '#f00') ? '#fff' : '#f00';
push @_,Tr({-style=>"background:$bkgcolor;color:$fntcolor"},
td([$_,"BACKGOUND COLOR IS $bkgcolor","FONT COLOR IS $fntcolor"]));
}

print table({-border=>1},@_), end_html;

Jeff Mott
04-07-2005, 02:18 PM
$bkgcolor = ($bkgcolor eq '#fff') ? '#f00' : '#fff';
$fntcolor = ($fntcolor eq '#f00') ? '#fff' : '#f00';At this point in the code $bkgcolor and $fntcolor have not been set to any value. They are, therefore, uninitialized. The need to initialize variables before they are used stems from the low-level principles where an unitialized variable does not get a special undefined value, but instead has garbage data that could be anything.

In this case you simply have to give $bkgcolor and $fntcolor some value (even the empty string will do).

CyCo
04-07-2005, 02:30 PM
Ok, Jeff Mott, thank you for that.

So, simply doing this will suffice?

my $bkgcolor = '';
my $fntcolor = '';

Jeff Mott
04-07-2005, 02:36 PM
Yup.

CyCo
04-07-2005, 02:47 PM
Excellent!
cheers

Nedals
04-08-2005, 01:39 AM
Or you can do it this way
my($bkgcolor,$fntcolor) = ('','');