ScaryAardvark
ScaryAardvark

Reputation: 2955

Why does my Perl program warn about an uninitialized value?

I've written the Perl script below which generates a warning and I can't work out why.

#!/usr/local/bin/perl -w

$status = $ENV{ 'STATUS' };
if ( $status eq "" )
{
    $status = 0;
}
else
{
    $status = 1;
}

It says "Use of uninitialized value in string eq at ./x.pl line 4."

Line 4 is the "if ( $status eq "" )" line, but the variable was initialised...

How can I get rid of this warning?

Upvotes: 2

Views: 5943

Answers (2)

Charles Ma
Charles Ma

Reputation: 49131

$ENV{'STATUS'} may not be defined.

If you run

export STATUS=blah

in the shell before running the Perl script, it will work.

Fix it with

#!/usr/local/bin/perl -w
$status = $ENV{ 'STATUS' };
if (!defined($status) || $status eq "" )
{
    $status = 0;
}
else
{
    $status = 1;
}

Upvotes: 6

Dave Sherohman
Dave Sherohman

Reputation: 46187

Another option is

$status = $ENV{ 'STATUS' } // '';

which will set $status to an empty string if it is not defined, but the // operator only exists in perl 5.10 and later. The equivalent pre-5.10 syntax is

$status = defined $ENV{STATUS} ? $ENV{STATUS} : '';

although a lot of people will fake it with

$status = $ENV{ 'STATUS' } || '';

but this will change an $ENV{STATUS} of 0 into an empty string, which may or may not be an issue for you.

Those are all general-case answers, however. In the particular code you posted, replacing the whole thing with

$status = defined $ENV{STATUS} ? 1 : 0;

or even just

$status = defined $ENV{STATUS};

(if you're OK with the 'not set' value being an empty string instead of 0) would be the better option.

Upvotes: 7

Related Questions