2017-06-03 60 views
-4

我的程序需要一个命令行参数,我想用它来改变我的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, $location\n"; 

if($application eq 'abc') { 
    #print "you came here\n"; 
    chdir "/viewstore/ccwww/dst_${application}_${version}/abc/${location}"; 
    print $ENV{PWD}; 
    print "you came here\n"; 
} 

我以前试过用chdir '/var/tmp/dst_$application/$version/$location';,但那也没用。

该代码的当前版本提供此警告。

全局符号“$ application_”需要在./test.pl第20行显式包名。由于编译错误,执行./test.pl时中止。

20行是chdir

+0

我已经尝试使用 – mahesh

+0

使用Getopt :: Std; my%opts =(); getopts('a:v:l:\%opts); my $ application = $ opts {a}; my $ version = $ opts {v}; my $ location = $ opts {l}; if($ application eq'abc') { chdir'/ var/tmp/dst_ $ application/$ version/$ location'; } – mahesh

+0

我在dst_ $应用程序附近出现异常,因为集中错误 – mahesh

回答

0

您在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是变量名。

+0

我已经尝试过双引号,但是这些值在脚本中没有被替换,我正在从命令行参数更新那些变量 – mahesh

+0

@mahesh请用您现在的代码更新您的问题。 – simbabque

+0

使用严格; 4使用警告; 6使用Getopt :: Std; 8 my%opts =(); 9 getopts('a:v:l:',\%opts); 10 my $ application = $ opts {a}; 11 my $ version = $ opts {v}; 12 my $ location = $ opts {l}; 14 print“$ application,$ version,$ location \ n”; 16 if($ application eq'abc') 18 { 19 #print“你来到了这里\ n”; 20 chdir“/ viewstore/ccwww/dst_ $ application_ $ version/abc/$ location”; 21 print“you came here \ n”; 22} – mahesh

相关问题