在我的Perl脚本中,我获得了可能包含环境变量的文件路径字符串,例如: $FONTS/test.ttf
或$TMP/file.txt
。
我现在想要打开这样的文件:
open my $handle, "<$filename" or die $!;
我现在如何在公开呼叫之前扩展环境变量,例如bash shell会做什么?
答案 0 :(得分:13)
如果设置了环境变量,则可以使用简单的替换:
$filename =~ s/\$(\w+)/$ENV{$1}/g;
答案 1 :(得分:2)
为什么不这样做:
$filename =~ s/\$\{(\w+)\}/$ENV{$1}/g;
$filename =~ s/\$(\w+)/$ENV{$1}/g;
答案 2 :(得分:0)
以下是相当冗长的,但它
似乎正确处理$FOO
和${FOO}
语法。
#!/usr/bin/env perl
use warnings;
use strict;
my $filename = $ARGV[0];
print(" GIVEN: <$filename>\n");
my $expanded = '';
my @parts = split(/(\$\w+)|(\${\w+})/, $filename);
foreach my $seg (@parts)
{
next if (not defined($seg));
$seg = ($ENV{$1} || '') if ($seg =~ m/\${?(\w+)}?/);
$expanded .= $seg;
}
print("IS NOW: <$expanded>\n");
print(`echo " ECHO: <$filename>"`); # How the shell did it.
这是一个样本运行...
$ ./expand '$TERM ---${TERM}--- ===${FOO}=== $FOO'
GIVEN: <$TERM ---${TERM}--- ===${FOO}=== $FOO>
IS NOW: <xterm-color ---xterm-color--- ====== >
ECHO: <xterm-color ---xterm-color--- ====== >
$
在此版本中,未定义的符号将替换为空字符串, 像shell一样。但在我的应用程序中,我宁愿离开未展开的 无效的符号到位,使您更容易看到出了什么问题。 此外,如果你搞砸你的支架匹配,外壳将 给你一个“糟糕的替代”错误,但在这里我们只会回来 带有破碎符号的字符串仍然存在。
答案 3 :(得分:0)
使用SHELL变量在perl中工作,正确的语法是:$ ENV {variable}
带有彩色GCC输出功能的示例:
n=$(tput setaf 0)
r=$(tput setaf 1)
g=$(tput setaf 2)
y=$(tput setaf 3)
b=$(tput setaf 4)
m=$(tput setaf 5)
c=$(tput setaf 6)
w=$(tput setaf 7)
N=$(tput setaf 8)
R=$(tput setaf 9)
G=$(tput setaf 10)
Y=$(tput setaf 11)
B=$(tput setaf 12)
M=$(tput setaf 13)
C=$(tput setaf 14)
W=$(tput setaf 15)
END=$(tput sgr0)
colorgcc()
{
perl -wln -M'Term::ANSIColor' -e '
m/not found$/ and print "$ENV{N}$`$ENV{END}", "$&", "$ENV{END}"
or
m/found$/ and print "$ENV{N}$`${g}", "$&", "$ENV{END}"
or
m/yes$/ and print "$ENV{N}$`${g}", "$&", "$ENV{END}"
or
m/no$/ and print "$ENV{N}$`$ENV{END}", "$&", "$ENV{END}"
or
m/undefined reference to/i and print "$ENV{r}", "$_", "$ENV{END}"
or
m/ Error |error:/i and print "$ENV{r}", "$_", "$ENV{END}"
or
m/ Warning |warning:/i and print "$ENV{y}", "$_", "$ENV{END}"
or
m/nsinstall / and print "$ENV{c}", "$_", "$ENV{END}"
or
m/Linking |\.a\b/ and print "$ENV{C}", "$_", "$ENV{END}"
or
m/Building|gcc|g\+\+|\bCC\b|\bcc\b/ and print "$ENV{N}", "$_", "$ENV{END}"
or
print; '
}