How do I set environment variables in Perl programs?

Perl environment FAQ: How do I set environment variables in Perl programs?

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 just do something 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.

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.

Setting Perl environment variables - an example program

You can test this with a quick example Perl environment variables program, like this:

#!/usr/bin/perl
# set the perl environment variable PATH
$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.

Perl environment variables - related tutorials

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

Thanks a lot. Was very useful

Thanks a lot.
Was very useful

Cheers

Cheers

Thanks

Thanks a lot, it really helped.

Post new comment

The content of this field is kept private and will not be shown publicly.