如何绕过无法修改的 Perl 库中的“死"调用? [英] How can I get around a 'die' call in a Perl library I can't modify?
问题描述
是的,问题出在我正在使用的库上,不,我无法修改它.我需要一个解决方法.
Yes, the problem is with a library I'm using, and no, I cannot modify it. I need a workaround.
基本上,我正在处理一个写得很糟糕的 Perl 库,它在读取文件时遇到某个错误条件时以die"退出.我从一个循环数千个文件的程序中调用这个例程,其中一些是坏的.坏文件发生;我只希望我的例程记录错误并继续.
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?
后续问题:使用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屋!