Perl错误捕获变量
我有一个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的名称?我试图使用某种全局变量而没有运气。
为什么不把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";
}
}
包括在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.
这将无法正常工作,因为错误来自获取链接,它永远不会写入。 – chrstahl89 2012-01-18 20:34:53
在你原来的问题中,我不清楚这一点。也就是说,当页面没有链接或链接可以找到时,follow-link返回undef。你可以抛出一个例外。 – JRFerguson 2012-01-18 20:50:30
我认为这将是答案,只需要弄清楚如何为此提出错误。那么赶上错误......它已经抛出它。 – chrstahl89 2012-01-18 21:05:32
If that's your only problem, just declare my $article;
的EVAL之前的文件名,并从for
环取出my
。但是从你对康奈尔吉林的回复中,我猜想它不是。
您的脚本不需要死亡,您可以将标记或保存消息设置为日志或存储错误以用于后期处理。
my @errors=();
................
open my $ofh, '>:raw', "$article.pdf" or do { push @errors,"$article: $!" };
if(-e $ofh) {
# work with the file
}
................
if(@errors) {
# do something
}
出于某种原因,当我这样做,它打印每一个PDF不只是那些等于从for循环 – chrstahl89 2012-01-18 20:34:26
ITYM'打印STDERR“错误处理文章$文章:$ @ \ n” $文章;'(不'$!')。你可以使用'warn'而不是'print STDERR'。但总的来说,这应该是工作;如果它不适用于@ chrstahl89,则问题可能在eval内。 – 2012-01-18 20:58:56
@ chrstahl89:你能发布“打印每个PDF”的实际代码吗? – 2012-01-18 21:04:32