http://qs321.pair.com?node_id=892986

saintmike has asked for the wisdom of the Perl Monks concerning the following question:

I'm using a library that acts on an %ENV variable being either set or not set. So, when I call it, I use

local $ENV{BLAH} = 42; libcall(); sub libcall { if( exists $ENV{BLAH} ) { print "env set to $ENV{BLAH}\n"; } else { print "env not set\n"; } }

and all is well, because the code within libcall() now sees $ENV{BLAH}'s value, while other parts of the system (outside the scope of the snippet above) aren't affected by the setting.

But now I want to add a condition in my code, to perform the setting only when another condition is met, but I can't use

if( condition() ) { local $ENV{BLAH} = 42; } libcall();

because the 'local' directive ends with the scope of the if-body and libcall() won't see it. I can't set the variable to undef because the library checks if the value exists(). I could obviously do

if( condition() ) { local $ENV{BLAH} = 42; libcall(); } else { libcall(); }

but that's lame because of the code duplication.

Is there a better way to 'local'ize a variable conditionally?