How to access shell environment variables in Perl script

Last updated on June 19, 2020 by Dan Nanni

Question: I would like to access several environment variables in my Perl script. How can I access shell variables from a Perl program?

In some cases you may want to access shell environment variables (e.g., $PATH, $PWD, $HOME, $LANG) in your Perl script. While you can pass any needed environment variables to your Perl script via @ARGV argument array, this is actually not needed since Perl provides a way to access all available environment variables. Let's find out how to access shell environment variables in a Perl script.

In Perl, all environment variables are maintained in a special hash named %ENV. To access a particular shell variable abc in Perl, you can simply fetch a hash value for key abc. For example, to access $PATH and $PWD variables in Perl:

my $path_var = $ENV{PATH};
my $pwd_var = $ENV{PWD};
print "PATH: $path_varn";
print "PWD: $pwd_varn";

Alternatively, you can use the Perl module called Env, which allows you to access shell environment variables using global Perl variables with the same names. For example, the above example code can be rewritten by importing Env module as follows.

use Env;

print "PATH: $PATH\n";
print "PWD: $PWD\n";

The Env module also allows you to import an environment variable as an array. For example:

use Env qw(@PATH);

foreach (@PATH) {
  print "$_n";
}

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean