我在系统托盘小程序中有以下初始化代码:
use Gtk3 -init;
use Glib::Object::Introspection;
eval {
Glib::Object::Introspection->setup(
basename => 'Notify',
version => '0.7',
package => "MyProgram::Notify",
);
};
if ($@) {
say "no notify because setup failed: $@";
$use_notify = 0;
} else {
MyProgram::Notify->init();
}
该代码基于fdpowermon,但似乎或多或少来自Glib::Object::Introspection 的 POD 中的异常处理示例。
但是 perlcritic(第 3 级)对此进行了争论:
Return value of eval not tested at line …
所以我尝试用 Try::Tiny 重写它:
use Gtk3 -init;
use Glib::Object::Introspection;
use Try::Tiny;
try {
Glib::Object::Introspection->setup(
basename => 'Notify',
version => '0.7',
package => "MyProgram::Notify",
);
} catch {
say "no notify because setup failed: $@";
$use_notify = 0;
} finally {
if (!$@) {
MyProgram::Notify->init();
}
}
但随后 perl 争辩说:
Can't locate object method "new" via package MyProgram::Notify::Notification
虽然我确实看到该finally
块并不是真正的改进,但我不明白为什么使用 Try::Tiny 会对 Glib::Object::Introspection 创建的包产生如此大的影响。
或者有没有比 Try::Tiny 更好的方法来让这段代码更优雅、更易读,同时保持perlcritic
快乐?