2010-11-19 62 views
1

我需要根據上一步的返回碼終止perl腳本。
perl中的錯誤級別

IF ERRORLEVEL 1 goto ERROR 

在批量處理。
我有

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

我需要的,如果這一步給出了錯誤,程序應該終止。
預先感謝您的意見。

+0

定義「這一步給出錯誤」?什麼構成錯誤?當你確定的時候,你會知道如何檢測它。 – Ether 2010-11-19 18:17:20

回答

4

其中分配給$PROG,添加此行的行後立即:

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

非常誘人的發佈只是'$?':) :) – ysth 2010-11-19 05:40:18

+0

的答案不起作用。代碼不起作用。 – ajay477 2010-11-19 11:33:30

+0

然後,'spu_comp'退出,返回值爲0. – cdhowie 2010-11-19 17:28:23

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. 
0

看來,ERRORLEVEL是不是一個真正的退出代碼到perl。

我有同樣的問題。的

@Echo OFF 
echo setting error level 1 
EXIT /B 1 

BAT文件隨着

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

一個perl文件產量

Error Level: 0 
Command: 

輸出的

#!/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"; 

一個Perl文件將產生

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:\> 
+0

它現在可以工作,但它可以在一臺機器上使用EXIT/B錯誤代碼,而在另一臺機器上不使用/ B。而不是相反。 – Tristan 2010-12-13 19:43:34

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 
} 
0

繼@脫殼機的答案,這是值得注意的$?僅適用於代碼爲255或更少。 Windows error codes通常超過這個。然而,IPC::System::Simple模塊提供瞭如capture()這樣的方法,其可以正確地檢索大於255的代碼。

例如,

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");