Environment and %ENV

Reading %ENV

Perl exposes the process environment as the hash %ENV. It is a normal-looking hash, but every read goes to the real environment, so values are always current.

use strict; use warnings; print "user: $ENV{USER}\n"; print "home: $ENV{HOME}\n"; print "shell: $ENV{SHELL}\n"; print "no HOME\n" unless exists $ENV{HOME};

USER=ada HOME=/home/ada SHELL=/bin/bash perl env.pl

user: ada
home: /home/ada
shell: /bin/bash

The command sets the three variables, so this page can show one fixed run; on your machine the same program prints your own values.

The whole list is one hash, so you can dump it when debugging a deployment: print "$_=$ENV{$_}\n" for sort keys %ENV. Do that on a server carefully, since the output can contain tokens.

Changing the environment

Assigning to %ENV changes the environment of the current process and of every program it starts later. Deleting a key removes the variable from children.

$ENV{APP_ENV} = "test"; $ENV{NO_COLOR} = 1; delete $ENV{DEBUG}; system("env");

The child inherits exactly this modified set. That is the usual way to pass configuration to a program you launch without adding flags to its command line.

To change one variable for a block of code and then restore it, use local. The old value comes back automatically when the block exits, even if the block dies:

{ local $ENV{APP_ENV} = "test"; system("prove", "-l", "t/"); } print "back to $ENV{APP_ENV}\n";

Defaults and paths

The defined-or operator turns a possibly missing variable into a usable value in one line, without a warning when the key is absent:

my $log = $ENV{LOG_FILE} // "/var/log/app.log"; my $port = $ENV{PORT} // 8080;

Note the difference from ||: defined-or keeps an empty string, while logical-or replaces it. For a port number you probably want to reject the empty string as well, so validate after reading instead of guessing.

PATH is a list glued together with a separator, a colon on Unix and a semicolon on Windows. Ask Config for the separator rather than hardcoding it:

use Config; my @dirs = split /\Q$Config{path_sep}\E/, $ENV{PATH}; print "$_ is on PATH\n" for @dirs;

The same idea applies to the home folder, which has a different name on Windows. Build a small helper once and use it everywhere:

sub home_dir { return $ENV{HOME} // $ENV{USERPROFILE} // die "cannot find the home folder\n"; }

Secrets and portability

Environment variables are convenient for configuration, but they are a poor place for passwords. On Linux any user who can see the process can read /proc/PID/environ, and the value is inherited by every child process, including ones that log their own environment.

Prefer a config file with tight permissions, or a secret manager that hands the value to the process that needs it. If you must use a variable, set it immediately before the one command that needs it and unset it afterwards.

local $ENV{PGPASSWORD} = $secret; system("psql", "-c", "select 1"); delete $ENV{PGPASSWORD};

Names are case-sensitive on Unix and case-insensitive on Windows, so read one exact spelling and do not rely on PATH versus Path. Under taint mode %ENV starts empty for security, which is another reason not to build a program that cannot run without it.

Finally, remember that environment variables are invisible to the person running your script next month. Print the effective settings at startup when --verbose is on, and document every variable you read in the help page.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is %ENV in Perl?

    Answer

    The process environment as a hash, whose reads always go to the real environment

    Each read and write reaches the process environment itself, which is why a change is visible to the children the program starts later.

  2. A program assigns to $ENV{APP_ENV} and then starts a child. What does the child see?

    Answer

    The new value, because the child inherits the modified environment

    The operating system copies the environment of the parent into the child at the moment the child starts.

  3. How do you change an environment variable for one block and restore the old value after it?

    Answer

    Declare local $ENV{NAME} inside the block

    The localised value comes back when the block ends, even when the block dies on the way.

  4. What is the difference between $ENV{X} // "default" and $ENV{X} || "default"?

    Answer

    // keeps an empty string, || replaces it too

    Defined-or tests definedness, while logical-or treats the empty string and 0 as false as well.

  5. Why are environment variables a poor place for a password?

    Answer

    Other users may read them through the process table, and every child inherits them

    A config file with tight permissions or a secret manager keeps the value out of the process table and out of the children.

  6. What does this program print? $ENV{PORT} = 3000; my $port = $ENV{PORT} // 8080; print $port, "\n";

    Answer

    3000

    The hash holds 3000, so the defined-or operator keeps it and the default is never used.

  7. What does this program print? $ENV{APP_ENV} = "test"; { local $ENV{APP_ENV} = "dev"; print "$ENV{APP_ENV}\n"; } print "$ENV{APP_ENV}\n";

    Answer

    dev / test

    The inner value lasts only for the block, and the outer value comes back afterwards.

  8. What does this program print? delete $ENV{DEBUG}; print exists $ENV{DEBUG} ? "set\n" : "unset\n";

    Answer

    unset

    The delete removes the key, so exists is false when the line after it runs.

  9. What does this program print? $ENV{NO_COLOR} = 1; print $ENV{NO_COLOR} + 1, "\n";

    Answer

    2

    The value is a string in the environment, and the addition turns it back into the number 1.

  10. What does this program print? my $empty = ""; my $a = $empty // "default"; my $b = $empty || "default"; print "$a|$b\n";

    Answer

    |default

    The empty string is defined, so // keeps it, while || treats it as false and replaces it.

Article author: Arthur Isaev