如何将变量从命令行参数插入到字符串中



我的程序采用了一个命令行参数,我想用它来更改我的perl脚本的工作目录。

use strict; 
use warnings;
use Getopt::Std; 
use Cwd 'chir';
my %opts=(); 
getopts('a:v:l:', %opts); 
my $application = $opts{a}; 
my $version = $opts{v}; 
my $location = $opts{l}; 
print "$application, $version, $locationn"; 
if($application eq 'abc') {
    #print "you came heren"; 
    chdir "/viewstore/ccwww/dst_${application}_${version}/abc/${location}";
    print $ENV{PWD}; 
    print "you came heren"; 
}

我以前尝试过使用chdir '/var/tmp/dst_$application/$version/$location';,但这也不起作用。

当前版本的代码发出了此警告。

全局符号" $ application_"要求在./test.pl行20中明确的软件包名称。

第20行是chdir

您在 chdir命令中使用单个引号 ''。单引号不会在Perl中进行可变的插值。这意味着'/var/tmp/dst_$application/...'表示/var/tmp/dst_$application/...,而不是/var/tmp/dst_foo/...

您需要使用双引号""在字符串中插值变量。

chdir "/var/tmp/dst_$application/$version/$location";

这将创建/var/tmp/dst_foo/...

如果您需要将变量与字符串的其余部分分开,请使用此符号。

print "${foo}bar";

这与"$foobar"不同,因为Perl认为整个$foobar是可变名称。

最新更新