2011-10-26 76 views
5

我有一個模塊需要在BEGIN塊中進行一些檢查。這可以防止用戶看到一行無用的消息(在編譯階段,這裏在第二個BEGIN中看到)。禁止「BEGIN失敗 - 編譯中止」

問題是,如果我死在BEGIN裏面,我扔的消息被埋在後面 BEGIN failed--compilation aborted at。不過,我更喜歡dieexit 1,因爲那樣它就可以被捕獲。我應該只使用exit 1或者我可以做些什麼來壓制這些額外的信息?

#!/usr/bin/env perl 

use strict; 
use warnings; 

BEGIN { 
    my $message = "Useful message, helping the user prevent Horrible Death"; 
    if ($ENV{AUTOMATED_TESTING}) { 
    # prevent CPANtesters from filling my mailbox 
    print $message; 
    exit 0; 
    } else { 

    ## appends: BEGIN failed--compilation aborted at 
    ## which obscures the useful message 
    die $message; 

    ## this mechanism means that the error is not trappable 
    #print $message; 
    #exit 1; 

    } 
} 

BEGIN { 
    die "Horrible Death with useless message."; 
} 

回答

10

當你die你正在拋出一個異常,在先前的調用級別被捕獲。從BEGIN塊中獲得die的唯一處理程序是編譯器,它會自動附加您不需要的錯誤字符串。

爲了避免這種情況,你可以使用exit 1解決方案,您找到,也可以安裝一個新的芯片處理程序:

# place this at the top of the BEGIN block before you try to die 

local $SIG{__DIE__} = sub {warn @_; exit 1}; 
+0

謝謝!現在我所得到的是: '在配置Alien :: GSL之前,某些需要的模塊缺失或必須升級。 這些模塊是:\t Sort :: Versions' –

+0

我應該說,這就是我想要的! –