简体   繁体   English

在 Perl 中设置环境变量的优雅方式

[英]Elegant way to set an environment variable in Perl

In my Perl script, I'm trying to set an environment variable (for example PATH ).在我的 Perl 脚本中,我正在尝试设置一个环境变量(例如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?在 Perl 中有没有更好更优雅的方法来做到这一点? Maybe a one liner?也许一个班轮? Note that the env does not have to be PATH .请注意,环境不必是PATH

If you use the Env Core module:如果您使用Env Core 模块:

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} ).我可能会写这样的东西,我使用长度来确定要添加的内容(尽管我不希望“0”成为$ENV{PATH}的值)。 The Config module knows what the path separator should be: Config模块知道路径分隔符应该是什么:

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} .基于Mathias 的回答,它基本上使用split作为 hack 来为$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.它检查变量中的值是否为假,在 Perl 标量中,它基本上意味着空字符串、未定义或零。 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.从技术上讲, 0可能是一条有效的路径,但感觉不太可能是一条正确的路径。

I would use split and join like this:我会像这样使用splitjoin

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM