Perl技术问题:实现$testScript调用时动态替换$TestVarDirName
Perl脚本动态变量替换问题解决
问题核心
你定义的$testScript是双引号字符串,Perl会在字符串初始化时完成变量插值。因为初始化时$TestVarDirName是空值,所以$testScript里对应位置始终是空,后续给$TestVarDirName赋值也不会自动更新这个字符串。
解决方案
方案1:占位符动态替换
把命令改成带占位符的模板,每次使用时用最新的$TestVarDirName替换占位符:
my $TestVarDirName; # 定义带占位符的命令模板 my $testScriptTemplate = "U:/perl.exe U:/devAuto.pl -p SHELL=/usr/bin/bash %TestVarDirName% -t lnx64"; runAndMonitor(\@ForRun, "$MSROO/logs/Test.log", $testScriptTemplate); # 新增的命令模板 my $testScriptTemplate2 = "U:/perl.exe U:/devAuto.pl -p SHELL=/usr/hash -m win -serial 32 %TestVarDirName% -t wint"; runAndMonitor(\@ForRun2, "$MSROO/logs/Test2.log", $testScriptTemplate2); sub runAndMonitor { my $ForRunRef = $_[0]; my $logFile = $_[1]; my $scriptTemplate = $_[2]; my @ForRunPerProduct = @{$ForRunRef}; foreach my $TestVar (@ForRunPerProduct) { $TestVarDirName = dirname($TestVar); # 动态替换占位符生成当前命令 my $testScript = $scriptTemplate; $testScript =~ s/%TestVarDirName%/$TestVarDirName/g; print "$testScript is the testScript command\n"; my $filehandle; if (!($pid = open($filehandle, "-|" , " $bashexe -c \"cd $smokesBasePath \; $testScript \" >> $logFile "))) { die( "Failed to start process: $!" ); } } }
方案2:用匿名子程序生成命令(更灵活)
把命令逻辑封装成匿名子程序,每次调用时传入最新的$TestVarDirName生成命令字符串:
my $TestVarDirName; # 定义生成命令的匿名子程序 my $getTestScript = sub { my $dir = shift; return "U:/perl.exe U:/devAuto.pl -p SHELL=/usr/bin/bash $dir -t lnx64"; }; runAndMonitor(\@ForRun, "$MSROO/logs/Test.log", $getTestScript); # 新增的命令生成器 my $getTestScript2 = sub { my $dir = shift; return "U:/perl.exe U:/devAuto.pl -p SHELL=/usr/hash -m win -serial 32 $dir -t wint"; }; runAndMonitor(\@ForRun2, "$MSROO/logs/Test2.log", $getTestScript2); sub runAndMonitor { my $ForRunRef = $_[0]; my $logFile = $_[1]; my $scriptGenerator = $_[2]; my @ForRunPerProduct = @{$ForRunRef}; foreach my $TestVar (@ForRunPerProduct) { $TestVarDirName = dirname($TestVar); # 调用生成器得到最新命令 my $testScript = $scriptGenerator->($TestVarDirName); print "$testScript is the testScript command\n"; my $filehandle; if (!($pid = open($filehandle, "-|" , " $bashexe -c \"cd $smokesBasePath \; $testScript \" >> $logFile "))) { die( "Failed to start process: $!" ); } } }
额外提示
Perl里调用子程序不需要加&符号,直接写runAndMonitor(...)即可,&属于旧写法,建议避免使用。
内容的提问来源于stack exchange,提问作者PPP
相关产品推荐
相关产品推荐

