george kushner george kushner - 9 months ago 44
Perl Question

How to make eval to return zero instead of nothing?

I am trying to evaluate a set of environment variables before proceeding with the code any further
Here is the piece:

for my $var qw(ENV_VAR1 ENV_VAR2 ENV_VAR3) {
my $value = eval '$ENV{"$var"}';
print "$var = $value\n";
die "$var not defined, exiting .." unless $value;

It throws an error for the print line:

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

Does it mean that
actually returns nothing? How to make it return zero or maybe the whole piece can be done in a better way?

Strangely enough, if I define and then undefine the variable in the underlying ksh (e.g.
export ENV_VAR1=anything;export ENV_VAR1=;
) then it duly dies with the correct message but then it gives me another
uninitialized value
for the next variable.

Answer Source

Your code won't compile. It needs additional parentheses around qw( ... )

There is no need for eval here. You just need to fetch the renvironment variable with $ENV{$var}, which will be undef if there is no such variable

It is very simple to test to an undefined value and behave accordingly, perhaps like this?

for my $var ( qw/ ENV_VAR1 ENV_VAR2 ENV_VAR3 / ) {

    my $value = $ENV{$var};

    die "\$value not defined, exiting .." unless defined $value;

    print "\$var = $value\n";

If you use export ENV_VAR1= then you are setting the variable to the empty string, and $ENV{ENV_VAR1} will be defined, but have a length of zero. To remove the environment variable, you need to unset ENV_VAR1, when $ENV{ENV_VAR1} will become undefined