perlexists

Check if an environment variable is set in Perl


I have been using

if(exists $ENV{VARIABLE_NAME} && defined $ENV{VARIABLE_NAME}) in several places my Perl script.

I feel it clutters the code and so assigned its value to a variable.

$debug = $ENV{VARIABLE_NAME};

But, now I can’t check for exists on a scalar value. Is there a way I can check exists for a scalar value?


Solution

  • There's no concept of exists for a scalar; for a hash, it tells you whether a given key appears in the hash (e.g., whether keys %ENV will contain it), but that's meaningless for a scalar.

    But in the specific case of an environment variable, you don't need the exists test anyway: environment variables are always strings, so they are never undef unless they haven't been set — making exists equivalent to defined for them. So you can just write if(defined $ENV{'VARIABLE_NAME'}) or if(defined $debug).