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

Hello monks. I come back to the well once again with a question. In some of our corporate code we use this..

$ENV{'PATH'} = '/bin:/usr/bin'; delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

Reason is for taint checking. If I were to follow best practices and localize this wouldn't that defeat the purpose?

I know that by not localizing $ENV that there exists a possibility of other things like modules in the script exhibiting unpredictable behavior.Any insight?

Replies are listed 'Best First'.
Re: Localizing Magic Variable? Should I?
by ikegami (Patriarch) on Nov 17, 2009 at 22:43 UTC

    If you were to localize them in stead of deleting them

    First of all, localizing *them* wouldn't be equivalent. They'd still exist in the hash (with undef for value) rather than not existing at all.

    Mind you, you can work around that:

    local %ENV = %ENV; $ENV{'PATH'} = '/bin:/usr/bin'; delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

    Or in 5.12+:

    local $ENV{'PATH'} = '/bin:/usr/bin'; local delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

    That said, do you have a reason to restore %ENV? If not, why would you localize it.

Re: Localizing Magic Variable? Should I?
by JavaFan (Canon) on Nov 17, 2009 at 22:18 UTC
    If you localize it so other code could still use the original values, then there's the distinct possibility said other code will die because it will use tainted values in a possible unsafe way.

    I would say that it's the task of the code that sets the taint flag to clean %ENV. Note also that %ENV is populated with data provided by the environment. Said other module might exhibit unpredicatable behaviour anyway if it wasn't your code that set $ENV{PATH}, but the environment.