start page | rating of books | rating of authors | reviews | copyrights

Book HomeLearning Perl, 3rd EditionSearch this book

14.3. The Environment Variables

When you're starting another process (with any of the methods discussed here), you may need to set up its environment in one way or another. As we mentioned earlier, you could start the process with a certain working directory, which it inherits from your process. Another common configuration detail is the environment variables.

The best-known environment variable is PATH. (If you've never heard of it, you probably haven't used a system that has environment variables.) On Unix and similar systems, PATH is a colon-separated list of directories that may hold programs. When you type a command like rm fred, the system will look for the rm command in that list of directories, in order. Perl (or your system) will use PATH whenever it needs to find the program to run. If the program in turn runs other programs, those may also be found along the PATH. (Of course, if you give a complete name for a command, such as /bin/echo, there's no need to search PATH. But that's generally much less convenient.)

In Perl, the environment variables are available via the special %ENV hash; each key in this hash represents one environment variable. At the start of your program's execution, %ENV holds values it has inherited from its parent process (generally the shell). Modifying this hash changes the environment variables, which will then be inherited by new processes and possibly used by Perl as well. For example, suppose you wished to run the system's make utility (which typically runs other programs), and you want to use a private directory as the first place to look for commands (including make itself). And let's say that you don't want the IFS environment variable to be set when you run the command, because that might cause make or some subcommand do the wrong thing. Here we go:

$ENV{'PATH'} = "/home/rootbeer/bin:$ENV{'PATH'}";
delete $ENV{'IFS'};
my $make_result = system "make";

Newly created processes will generally inherit from their parent the environment variables, the current working directory, the standard input, output, and error streams, and a few more-esoteric items. See the documentation about programming on your system for more details. (But your program can't change the environment for the shell or other parent process that started it, on most systems.)



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.