http://www.perlmonks.org?node_id=198414

anzalone has asked for the wisdom of the Perl Monks concerning the following question: (programs and processes)

I want to set an environment variable from within the perl script so that it's visible to other subsequent processes, like what export var=xyz does in unix shells.
Something like $ENV{'var'} = 'xyz' has effect only for the current process and any children it spawns.

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How to set an environment variable in perl so that it's visible to subsequent processes?
by jdporter (Paladin) on Dec 15, 2006 at 13:31 UTC
Re: How to set an environment variable in perl so that it's visible to subsequent processes?
by anzalone (Initiate) on Sep 17, 2002 at 18:36 UTC

    On Windows, you can use the Win32::AdminMisc module (by Dave Roth, not on CPAN), which has a function for this, SetEnvVar:

    SetEnvVar( $Name, $Value [, $Type [, $Timeout ] ] )

    This will set an environment variable $Name to $Value. This function will set the variable (creating it if $Name does not exist).
    The new value will be set globally so all applications will be able to use it, unlike setting $ENV{xxx} — which sets the variable for the current process and any children it spawns afterwards.
    When this function is called a broadcast to all running applications is made telling them about the variable change. An application may choose to ignore the change if it was programmed to do so.
    If $Timeout is specified then the broadcast announcement will be aborted if it takes longer than $Timeout seconds (some applications may be in a hung state so they can not acknowledge the broadcast). If this timeout occurs the variable will still be updated but broadcasting it's change will be aborted.
    If $Type is specified it can be one of:

    ENV_SYSTEM
    Specifies that $Name will be a system environment variable. (default if $Type is not specified)
    ENV_USER
    Specifies that $Name will be a user environment variable.

    This function is the equivalent to setting an environment variable in the control panel's system applet.

    NOTE: Your script will not see the new value. For that you should set $ENV{xxx}.

    Example:

    Win32::AdminMisc::SetEnvVar( "Temp", "$ENV{HOMEDRIVE}$ENV{HOMEPATH}", +ENV_USER, 10 );

    Returns:

    0 if not successful
    1 if successful

    Win32::AdminMisc also has a DelEnvVar function for deleting environment variables.

Re: perl "use env;" and exporting variables
by heeru (Initiate) on Dec 15, 2006 at 11:34 UTC
    How can we do the same for LINUX?

    Originally posted as a Categorized Answer.