Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: check if environment variable is set [duplicate]

Tags:

perl

exists

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?

like image 490
iDev Avatar asked Nov 28 '22 21:11

iDev


2 Answers

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).

like image 118
ruakh Avatar answered Dec 10 '22 03:12

ruakh


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.

like image 37
David Knipe Avatar answered Dec 10 '22 03:12

David Knipe