如何在Perl库中找到一个“死”电话,我无法修改? [英] How can I get around a 'die' call in a Perl library I can't modify?

查看:150
本文介绍了如何在Perl库中找到一个“死”电话,我无法修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,问题是我正在使用的图书馆,不,我不能修改它。我需要一个解决方法。

Yes, the problem is with a library I'm using, and no, I cannot modify it. I need a workaround.

基本上,我正在处理一个写得不好的Perl库,当读取文件时遇到一个特定的错误条件,它将以死的形式退出。我从一个循环了数千个文件的程序中调用这个例程,其中几个是坏的。坏文件发生;我只是想让我的日志记录一个错误,继续前进。

Basically, I'm dealing with a badly written Perl library, that exits with 'die' when a certain error condition is encountered reading a file. I call this routine from a program which is looping through thousands of files, a handful of which are bad. Bad files happen; I just want my routine to log an error and move on.

如果我可以修改库,我只需更改

IF I COULD modify the library, I would simply change the

die "error";

print "error";return;

,但我不能。有没有什么办法可以把这个例程放在一起,这样糟糕的文件就不会崩溃整个过程?

, but I cannot. Is there any way I can couch the routine so that the bad files won't crash the entire process?

FOLLOWUP问题:使用eval倾斜的电话工作很好,但是如何在该框架内设置可捕获错误的处理?要描述:

FOLLOWUP QUESTION: Using an "eval" to couch the crash-prone call works nicely, but how do I set up handling for catch-able errors within that framework? To describe:

我有一个子程序调用库 - 哪些崩溃 - 有时很多次。而不是在这个子例程中使用eval {}调用这个子例程,我只是让它死机,并在调用子程序的级别上使用eval {}:

I have a subroutine that calls the library-which-crashes-sometimes many times. Rather than couch each call within this subroutine with an eval{}, I just allow it to die, and use an eval{} on the level that calls my subroutine:

my $status=eval{function($param);};
unless($status){print $@; next;}; # print error and go to next file if function() fails

但是,有错误的条件,我可以在function()中捕获。在子程序和调用例程中设计错误捕获的最合适/优雅的方法是什么,以便捕获和未捕获的错误获得正确的行为?

However, there are error conditions that I can and do catch in function(). What is the most proper/elegant way to design the error-catching in the subroutine and the calling routine so that I get the correct behavior for both caught and uncaught errors?

推荐答案

您可以将它包装在一个 eval 中。参见:

You could wrap it in an eval. See:

perldoc -f eval

例如,你可以写:

# warn if routine calls die
eval { routine_might_die }; warn $@ if $@;

这将会将致命错误转为警告,这或多或少是您建议的。如果 die 被调用, $ @ 包含传递给它的字符串。

This will turn the fatal error into a warning, which is more or less what you suggested. If die is called, $@ contains the string passed to it.

这篇关于如何在Perl库中找到一个“死”电话,我无法修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆