Reputation: 6011
How do I set an environment variable in Perl?
I want to set HOME
to a different directory than the default.
Upvotes: 21
Views: 45614
Reputation: 177
When the Perl executable gets started, it makes it own subshell. 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, we can not set an environment path for the main shell as Perl's instance will be like subshell of the main shell. Child process can not set environment paths for parents.
Now till Perl's sub shell will run, you'll be able to access all the paths present in your temp.csh file.
Upvotes: 1
Reputation: 3044
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.
Upvotes: 2
Reputation: 47889
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.
Upvotes: 41
Reputation: 5
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.
Upvotes: -4