Elegant way to set an environment variable in Perl

Viewed 911

In my Perl script, I'm trying to set an environment variable (for example PATH). In case it's already defined, add the path to it. Otherwise, set the env. The code:

if (defined($ENV{"PATH"})) {
    $ENV{"PATH"} = $ENV{"PATH"}.":/usr/pkgs/";
} else {
    $ENV{"PATH"} = "/usr/pkgs/";
}

Is there a better and elegant way to do this in Perl? Maybe a one liner? Note that the env does not have to be PATH.

4 Answers

If you use the Env Core module:

use warnings;
use strict;
use Env qw(@PATH);

push @PATH, '/usr/pkgs/';

I'd probably write something like this, where I use the length to determine what to add on (although I don't expect "0" to ever be the value of $ENV{PATH}). The Config module knows what the path separator should be:

use Config qw(%Config);

$ENV{PATH} .= ( length $ENV{PATH} ? $Config{path_sep} : '' ) . "/usr/pkgs/";

Based on Mathias' answer, which basically uses split as a hack to create an empty list for empty values in $ENV{PATH}. You can use the simpler check || which checks if the value in the variable is false, which in a Perl scalar means basically empty string, undefined or zero. Since we want to avoid the possibility of adding a colon to the start of the string, we want to replace it with the empty list (). So it becomes:

$ENV{PATH} = join ":", $ENV{PATH} || (), "/usr/pkgs/";

Technically, 0 could be a valid path, but it feels unlikely to be a correct path.

I would use split and join like this:

$ENV{PATH} = join(":", split(/:/, $ENV{PATH}), "/usr/pkgs")
Related