如何从环境变量中提取$符号?

时间:2014-01-27 04:54:12

标签: arrays perl environment-variables

我有一个包含诸如

等行的文本文件
$ENVGEN/path/to/file

ENVGEN是指环境变量,我需要在环境设置中使用ENVGEN的实际值重新评估此行。

我可以将$ENVGEN字符串分离到数组的独立元素,但我仍需要对其进行评估并重新构建路径。

3 个答案:

答案 0 :(得分:1)

一般情况下,

s/\$([A-Z_a-z][A-Z_a-z0-9]*)/ $ENV{$1} || "\$$1" /gex;

将使用它们的值替换明显的环境变量,并且(似乎)如果它们未在环境中定义则保持不变。

答案 1 :(得分:0)

Perl将环境变量保存在名为%ENV的特殊哈希中,它不是数组。您可以使用$ENV{'ENVGEN'}检索它。

例如,

#!/usr/bin/env perl
print "PATH=".$ENV{'PATH'}."\n";
print "ENVGEN=".$ENV{'ENVGEN'};

修改即可。用其值

替换对env变量的引用
# say we read a line from a file, and we got this:
my $line_from_file = '$ENVGEN/path/to/file';

# split the path to components
my @path_components = split('/', $line_from_file);

# the first component is known to refer to an env variable,
# replace it with its value, chopping the '$' character from
# the start of the variable description
$path_components[0] = $ENV{substr($path_components[0], 1)};

# join the components back to form the re-evaluated path
$path_to_file = join('/', @path_components); 

答案 2 :(得分:0)

您可以使用String::Interpolate

# FOO = $BAR/to/file
# BAR = /path

use String::Interpolate;
my $foo = String::Interpolate::interpolate($ENV{'FOO'}, \%ENV);
print "$foo\n"; # /path/to/file
相关问题