Moose、Try::Tiny 和 TryCatch 的奇怪行为
我刚刚开始与 Moose 合作,遇到了一个我无法解决的奇怪问题。以下代码:
#!/usr/bin/env perl
use strict;
use warnings;
use Try::Tiny;
{
package Foo;
use Moose;
has x => ( is => 'ro', isa => 'Int' );
}
my $f;
try {
$f = Foo->new(x => 'x');
} catch {
die "oops\n";
}
print $f->x . "\n";
产生:
Can't call method "x" on an undefined value at m2.pl line 19.
但是,如果我用 TryCatch
替换 Try::Tiny
,它的行为就像我假设的那样:
oops
即使 x
> 是正确的值,比如 5
,Try::Tiny
仍然会产生 undefined value
错误。
由于我阅读的所有 Moose 文档都使用 Try::Tiny
,我很困惑为什么这段代码不起作用。我在这里做错了什么吗?
I've just started working with Moose and have run into an odd problem that I cannot figure out. The following code:
#!/usr/bin/env perl
use strict;
use warnings;
use Try::Tiny;
{
package Foo;
use Moose;
has x => ( is => 'ro', isa => 'Int' );
}
my $f;
try {
$f = Foo->new(x => 'x');
} catch {
die "oops\n";
}
print $f->x . "\n";
produces:
Can't call method "x" on an undefined value at m2.pl line 19.
However, if I replace Try::Tiny
with TryCatch
, it acts as I would assume it should:
oops
Even if x
is the correct value, say 5
, Try::Tiny
still produces the undefined value
error.
As all of the Moose documentation I have been reading uses Try::Tiny
, I'm very confused on why this code isn't working. Am I doing something completely wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Try::Tiny
需要在 try/catch 节末尾有一个分号:这是由于
Try::Tiny
的实现 --try 和 catch 都只是函数。
Try::Tiny
requires a semicolon at the end of a try/catch stanza:This is due to the implementation of
Try::Tiny
--try
andcatch
are both just functions.try { ... } catch { ... } 不是内置函数(因为它是由模块提供的)。在 perl 5 中,这意味着您必须以分号结尾,如下所示:
我无法回答 TryCatch 如何设法处理丢失的分号 - 但可以使用各种黑魔法:)
try { ... } catch { ... } isn't a builtin (since it is provided by a module). In perl 5 this means that you have to end it with a semicolon like so:
I can't answer how TryCatch manages to handle the missing semicolon - but it is possible using various black magic :)