2012-01-18 63 views
0

我有一個Perl腳本,我試圖讓它打印出$ article的值,當它出錯時。該腳本看起來像:Perl錯誤捕獲變量

eval{ 
    for my $article($output =~ m/<value lang_id="">(.*?)<\/value>/g) 
    { 
     $article =~ s/ /+/g; 
     $agent->get("someurl"); 

     $agent->follow_link(url_regex => qr/(?i:pdf)/); 

     my $pdf_data = $agent->content; 
     open my $ofh, '>:raw', "$article.pdf" 
     or die "Could not write: $!"; 
     print {$ofh} $pdf_data; 
     close $ofh; 
     sleep 10; 
    } 
}; 
if([email protected]){ 
    print "error: ...: [email protected]\n"; 
} 

因此,如果沒有.pdf文件代碼發送一個錯誤,這是我想要的。但是我需要知道的是,它有可能獲得導致錯誤的$ article的名稱?我試圖使用某種全局變量而沒有運氣。

回答

4

爲什麼不把eval放在for循環中?事情是這樣的:

for my $article($output =~ m/<value lang_id="">(.*?)<\/value>/g) 
{ 
    $article =~ s/ /+/g; 
    eval{ 
     # ... 
    } 
    if ([email protected]) { 
     print STDERR "Error handling article: ", $article, " ", $!, "\n"; 
    } 
} 
+0

出於某種原因,當我這樣做,它打印每一個PDF不只是那些等於從for循環 – chrstahl89 2012-01-18 20:34:26

+0

ITYM'打印STDERR「錯誤處理文章$文章:$ @ \ n」 $文章;'(不'$!')。你可以使用'warn'而不是'print STDERR'。但總的來說,這應該是工作;如果它不適用於@ chrstahl89,則問題可能在eval內。 – 2012-01-18 20:58:56

+0

@ chrstahl89:你能發佈「打印每個PDF」的實際代碼嗎? – 2012-01-18 21:04:32

0

包括在die>/ string:

open my $ofh, '>:raw', "$article.pdf" or die "Could not write '$article': $!"; 

I assume that you want to write and not read. Unless you have a permission issue or a full file system, a write is likely to succeed and you will never see an error.

+1

這將無法正常工作,因爲錯誤來自獲取鏈接,它永遠不會寫入。 – chrstahl89 2012-01-18 20:34:53

+0

在你原來的問題中,我不清楚這一點。也就是說,當頁面沒有鏈接或鏈接可以找到時,follow-link返回undef。你可以拋出一個例外。 – JRFerguson 2012-01-18 20:50:30

+0

我認爲這將是答案,只需要弄清楚如何爲此提出錯誤。那麼趕上錯誤......它已經拋出它。 – chrstahl89 2012-01-18 21:05:32

1

If that's your only problem, just declare my $article;的EVAL之前的文件名,並從for環取出my。但是從你對康奈爾吉林的回覆中,我猜想它不是。

0

您的腳本不需要死亡,您可以將標記或保存消息設置爲日誌或存儲錯誤以用於後期處理。

my @errors=(); 
................ 
open my $ofh, '>:raw', "$article.pdf" or do { push @errors,"$article: $!" }; 
if(-e $ofh) { 
    # work with the file 
} 
................ 
if(@errors) { 
    # do something 
}