How do I set an environment variable in Perl?

Viewed 35577

How do I set an environment variable in Perl?

I want to set $HOME to a different directory than the default.

5 Answers

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 useing 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.

Related