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


in reply to Re: How to localize conditionally?
in thread How to localize conditionally?

The library checks for existence, so that doesn't work. You'd need
local %ENV = condition ? (%ENV, BLAH=>42) : %ENV;

Replies are listed 'Best First'.
Re^3: How to localize conditionally? (tias)
by tye (Sage) on Mar 14, 2011 at 15:44 UTC

    Did you test it? It works for me.

    - tye        

      No, but how can one assign to a hash element that does not exist? Well, %ENV is magical, so let's test it out.

      $ perl -wE' my $condition = 0; say exists($ENV{BLAH}) || 0; local $ENV{BLAH} = $condition ? 42 : $ENV{BLAH}; say exists($ENV{BLAH}) || 0; ' 0 1

      So I was right

      This is perl 5, version 12, subversion 2 (v5.12.2) built for i686-linu +x

        My tests appeared to work for strange reasons. Sorry about that. But you can fix the original without copying the whole environment:

        local $ENV{BLAH}; if( @ARGV ) { $ENV{BLAH}= 42; } else { delete $ENV{BLAH}; }

        - tye