How do I set an environment variable in Perl?
I want to set $HOME
to a different directory than开发者_开发百科 the default.
You can do it like this:
$ENV{HOME} = 'something different';
But please note that this will only have an effect within the rest of your script. When your script exits, the calling shell will not see any changes.
As perldoc -v %ENV
says:
%ENV
The hash%ENV
contains your current environment. Setting a value in "ENV" changes the environment for any child processes you subsequently "fork()
" off.
$ENV{'HOME'} = '/path/to/new/home';
Also see perlrun
When perl gets started it makes it own sub shell. That sub shell does not contain all features like sourcing a shell file which are available only for main shells. You can not set any environment path for your main shell. You can do one thing if you have a shell file from where you want to access your paths you can use it in your code.
You can do this by installing external module from CPAN which is Shell::Source.
$env_path= Shell::Source->new(shell=>"tcsh",file=>"../path/to/file/temp.csh");
$env_path->inherit;
print "Your env path: $ENV{HOME}";
As perl creates its own instance while running on a shell, so we can not set environment path for the main shell as the perl's instance will be like sub shell of the main shell. Child process can not set environment paths for parents.
Now till the perl's sub shell will run you'll be able to access all the paths present in your temp.csh
If you need to set an environment variable to be seen by another Perl module that you're importing, then you need to do so in a BEGIN
block.
For example, if use
ing DBI (or another module that depends on it, like Mojo::Pg), and you want to set the DBI_TRACE
environment variable in your script:
use DBI;
BEGIN {
$ENV{DBI_TRACE}='SQL';
}
Without putting it in a BEGIN
block, your script will see the environment variable, but DBI
will have already been imported before you set the environment variable.
It's cheesy, but you could call a VBS script using system("cscript your_vbs_script") to have it handle the environment variable assignment. It will exist for the next shell opened, not the running shell in that case.
精彩评论