2012-09-26 19 views
3

我喜歡跳過while(1)之後。怎麼做? 檢查特殊變量和last不正確,因爲while表達式包含阻止調用的,所以如果檢查表達式就太遲了。如何在while(1)之後通過SIGHUP在Perl中跳轉?

#!/usr/bin/perl 
use strict; 
use warnings; 
use feature qw(say); 
use sigtrap 'handler', \&hup_handler, 'HUP'; 
my $counter = 0; 
sub hup_handler { say 'HUP!!!'; $counter = 0; return; } 
say 'It starts here'; 
while (1) { 
    sleep(1); # Blocking call is in reality within while expression. 
    say ++$counter; 
} 
say 'It ends here'; 
+0

你是什麼意思?你的意思是打破循環?嘗試休息; –

+3

@Perroloco這是一個Perl問題。 Perl中沒有'break'命令(在循環的上下文中)。 – simbabque

+1

'last'以及任何**太遲**因爲'while'表達式中的**阻塞**調用。 – burnersk

回答

6

這應該拋出一個異常,亦稱死(),信號處理程序內是可能的。

所以嘗試做這樣的事情:

say 'It starts here'; 
eval { 
    local $SIG{HUP} = sub { say 'HUP!!!'; $counter = 0; die "*bang*"; } 

    while (1) { 
     sleep(1); # Blocking call is in reality within while expression. 
     say ++$counter; 
    } 
} 
say 'It ends here'; 

當然,任何模塊提供了一個比較正常的期待try/catch語句的語法會工作。 (1)之後跳什麼意思?

+0

它回答我的問題,謝謝:)但如果'* bang *'發生在評估之外我的程序死亡:'( – burnersk

+2

您可以在循環內移動信號處理程序,因爲我已將代碼更改爲。 sigtrap pragma,所以我不確定它是否能正確工作,而是直接使用%SIG。 – pmakholm

+0

超級非常感謝你 – burnersk