【问题标题】:How to extract $ symbol from environment variable?如何从环境变量中提取 $ 符号?
【发布时间】:2014-01-27 04:54:12
【问题描述】:

我有一个文本文件,其中包含以下行,

$ENVGEN/path/to/file

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

我可以将$ENVGEN 字符串分离为一个独立的数组元素,但我仍然需要评估它并重新形成路径。

【问题讨论】:

  • 提供可使用的示例数据。
  • 存储为数组的一个元素是什么意思?
  • 除了访问$ENV['ENVGEN'],你还在做什么?
  • $ENVGEN 存储到数组中。所以,如果我们逐字逐句,那么我如何从 $ENVGEN 中提取 $ 符号,然后我放入 $ENV{'ENVGEN'} 中,我可以获得价值。
  • 我有一个文件。在这个文件中给出了目录路径。像 $ENVGEN/xyc/yha/ 那么,如何获取目录的完整路径?

标签: arrays perl environment-variables


【解决方案1】:

一般情况下,

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

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

【讨论】:

    【解决方案2】:

    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); 
    

    【讨论】:

    • 我有一个文件。在这个文件中给出了目录路径。像 $ENVGEN/xyc/yha/。 $ENVGEN 是环境变量。那么,如何获取目录的完整路径?
    【解决方案3】:

    您可以为此使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-12
      • 2016-02-23
      • 2010-10-14
      • 2018-08-08
      • 2014-08-12
      • 2015-11-22
      • 1970-01-01
      • 2014-02-10
      相关资源
      最近更新 更多