Environment Variables in Perl

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in Perl.

use strict;
use warnings;
use Data::Dumper;

# To set a key/value pair, use $ENV
# To get a value for a key, use $ENV{key}
# This will return undef if the key isn't present in the environment
$ENV{FOO} = "1";
print "FOO: $ENV{FOO}\n";
print "BAR: ", ($ENV{BAR} || ""), "\n";

# Use keys %ENV to list all keys in the environment
# Here we print all the keys
print "\n";
foreach my $key (keys %ENV) {
    print "$key\n";
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ perl environment-variables.pl
FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 perl environment-variables.pl
FOO: 1
BAR: 2
...

In Perl, environment variables are accessed through the %ENV hash. Setting a value is as simple as assigning to a key in this hash, and reading a value is done by accessing the hash key. The keys %ENV function gives us all the keys in the environment.

Unlike Go, Perl doesn’t require explicit importing of modules for basic environment variable operations. However, we’ve used use strict and use warnings for better code quality, and use Data::Dumper for more complex data structure printing (though it’s not used in this simple example).

The || operator in the BAR print statement is used to provide a default empty string if $ENV{BAR} is undefined, which is similar to how Go’s os.Getenv returns an empty string for non-existent keys.