perl中的errorlevel

时间:2010-11-19 04:59:19

标签: perl perl-module

我需要根据上一步的返回码终止perl脚本

之类的东西
  IF ERRORLEVEL 1 goto ERROR  

批处理。
我有

$PROG = `spu_comp 2>&1 $a 1 1`;  

我需要如果这一步给出错误,程序应该终止 提前感谢您的意见。

5 个答案:

答案 0 :(得分:4)

在您分配到$PROG的行之后,立即添加以下行:

($? >> 8) and die "spu_comp exited with non-zero return value";

答案 1 :(得分:1)

$ perl -le'`sh -c "exit 0"`;($?>>8) and die "exited with non-zero: ", ($?>>8)'
$ perl -le'`sh -c "exit 1"`;($?>>8) and die "exited with non-zero: ", ($?>>8)'
exited with non-zero: 1 at -e line 1.

答案 2 :(得分:0)

似乎ERRORLEVEL不是perl的真正退出代码。

我有同样的问题。

的bat文件
@Echo OFF
echo setting error level 1
EXIT /B 1

使用perl文件

#!/usr/bin/perl
$command = `C:\foo.bat`;
print "Error Level: " .$? ."\n";
print "Command: " . $command . "\n";

产量

Error Level: 0
Command:

的perl文件
#!/usr/bin/perl

my $command = `dir`;#try both dir and dri to test real exit codes against batch exit codes
print "Error Level: " .$? ."\n";
print "Command: " . $command . "\n";

将产生

C:\>back.pl
'dri' is not recognized as an internal or external command,
operable program or batch file.
Error Level: 256
Command:

C:\>back.pl
Error Level: 0
Command:  Volume in drive C has no label.
 Volume Serial Number is 8068-BE74

 Directory of C:\

12/13/2010  11:02 AM                 7 8
06/02/2010  01:13 PM                 0 AUTOEXEC.BAT
06/04/2010  01:00 PM    <DIR>          AutoSGN
12/13/2010  12:03 PM               111 back.pl
06/02/2010  01:13 PM                 0 CONFIG.SYS
06/03/2010  07:37 PM    <DIR>          Documents and Settings
12/13/2010  12:01 PM                46 foo.bat
06/04/2010  03:17 PM    <DIR>          HorizonTemp
06/02/2010  02:41 PM    <DIR>          Intel
06/04/2010  02:19 PM    <DIR>          league
06/04/2010  12:31 PM    <DIR>          Perl
12/10/2010  03:28 PM    <DIR>          Program Files
12/08/2010  04:13 PM    <DIR>          Quarantine
12/13/2010  08:14 AM    <DIR>          WINDOWS
               5 File(s)            164 bytes
               9 Dir(s)  18,949,783,552 bytes free


C:\>

答案 3 :(得分:0)

您可以通过添加以下行从$ PROG获取正确的返回代码。

my $ret = $?/256   #/

或更清洁的方式

my $ret = $? >> 8;

然后将$ ret与您可以检索的可能值进行比较

if ($ret == 0)
{
   # Do something if finished successfully
}
elsif($ret == 1)
{
   error();
}
else
{
   # Return something else that was nor 0 nor 1
}

答案 4 :(得分:0)

除了@ husker的回答之外,值得注意的是$?仅适用于255或更低的代码。 Windows error codes通常会超出此范围。但是,IPC::System::Simple模块提供了capture()等可以正确检索代码的方法&gt; 255。

e.g。

use Test::More;
use IPC::System::Simple qw(capture $EXITVAL EXIT_ANY);
my $modeTest = capture(EXIT_ANY, "some command that sets error code 5020");
is( $EXITVAL , 5020, "Expect error code 5020" );