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.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
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.