Perl - How do I set environment variables?

Perl environment variables FAQ: How do I set environment variables in a Perl program?

In several other articles, we've demonstrated how you can access the value of environment variables from your Perl programs. For example, to determine the setting of your "PATH" environment variable, you can write a line of Perl code like this:

$path = $ENV{'PATH'};

As you may remember, "%ENV" is a special hash in Perl that contains the value of all your environment variables.

Using the Perl %ENV hash

Because %ENV is a hash, you can set environment variables just as you'd set the value of any Perl hash variable. Here's how you can set your PATH variable to make sure the following four directories are in your path::

$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/home/fred/bin';

You'll want to set your PATH like this if you have an executable program in /home/fred/bin that is required by your Perl program.

You can test this with a quick sample program, like this:

#!/usr/bin/perl

$ENV{'PATH'} = '/bin:/usr/bin:/home/fred/bin';
print $ENV{'PATH'};


I ran into this problem recently when a developer assumed that the Unix/C-shell which command was in my PATH, which it wasn't. I could have fixed this problem in several different ways, but decided to modify the PATH to find the which command in the /usr/ucb/ directory, like this:

$ENV{'PATH'} = '/bin:/usr/bin:/usr/ucb';

where it was located on that system.

If you're interested in environment variables, or how environment variables work with CGI programs, you might be interested in these local links: