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 cant check for exists
on a scalar value. Is there a way I can check exists for a scalar value?
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)
.
You're right that exists
is meaningless for a scalar variable. But couldn't you just write if(defined $ENV{VARIABLE_NAME})
? If it doesn't exist then $ENV{VARIABLE_NAME}
will return undef
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With