好的,我假设问题是:(a)当发生错误时,您想在某个对象中设置一个标志,然后在所有操作结束时检查该标志;(b)您的错误处理程序(在全局变量中)需要某种方式来知道要接触哪个对象。您可以使用一个闭包来实现这一点,如下所示:
#
# This part is the library that implements error handling a bit like
# SVN::Client
#
sub default_error_handler {
croak "An error occurred: $_[0]";
}
our $global_error_handler = \&default_error_handler;
sub library_function_that_might_fail {
&$global_error_handler("Guess what - it failed!");
}
#
# This part is the function that wants to detect an error
#
sub do_lots_of_stuff {
my $error = undef; # No errors so far!
local($global_error_handler) = sub { $error = $_[0]; };
library_function_that_might_fail();
library_function_that_might_fail();
library_function_that_might_fail();
if ($error) {
print "There was an error: $error\n";
}
}
#
# Main program
#
do_lots_of_stuff();
关键是,当
do_lots_of_stuff()
,我们将错误处理程序设置为匿名Sub,该Sub继续访问创建它的函数的局部变量,以便它可以修改
$error
表示发生了错误。