Perl environment variables - How to access Perl environment variables

Here's a quick example program that demonstrates how to access environment variables from within your Perl programs:

# environment variables are held in the %ENV hash
foreach $key (sort keys %ENV)
  print "$key is $ENV{$key}\n";

Using this simple Perl foreach loop, here's a subset of the output this script prints on my MacBook Pro:

ANT_HOME is /opt/local/share/java/apache-ant
DISPLAY is :0.0
HOME is /Users/al
JAVA_HOME is /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0
MANPATH is /sw/share/man:/opt/local/share/man:/sw/lib/perl5/5.8.8/man:/usr/X11R6/man
OLDPWD is /Users/al
PERL5LIB is /sw/lib/perl5:/sw/lib/perl5/darwin
SHELL is /bin/bash
TERM is xterm-color
TMPDIR is /var/folders/AB/ABWKCUeUHNC7+W0f7GZjXk+++TI/-Tmp-/
TOMCAT_HOME is /Users/al/tomcat-6.0.16
USER is al

The most important thing you need to remember here is that your current Perl environment variables are held in a Perl hash named %ENV. You can either access them in a loop, as shown above, or one environment variable at a time.

For instance, to access the value of just the SHELL environment variable, I would just access it like this:

print "SHELL is $ENV{'SHELL'}\n";

When dealing with hashes you also need to pay attention to some of the special characters. The environment hash is referred to as %ENV, but when you access a specific value within the hash you switch from the % symbol to the following syntax with a dollar sign and the curly braces: $ENV{'SHELL'}.