Moose、Try::Tiny 和 TryCatch 的奇怪行为

发布于 2024-11-15 10:11:09 字数 729 浏览 4 评论 0原文

我刚刚开始与 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 > 是正确的值,比如 5Try::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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北笙凉宸 2024-11-22 10:11:09

Try::Tiny 需要在 try/catch 节末尾有一个分号:

try {
    $f = Foo->new(x => 'x');
} catch {
    die "oops\n";
};

这是由于 Try::Tiny 的实现 -- try 和 catch 都只是函数。

Try::Tiny requires a semicolon at the end of a try/catch stanza:

try {
    $f = Foo->new(x => 'x');
} catch {
    die "oops\n";
};

This is due to the implementation of Try::Tiny -- try and catch are both just functions.

っ〆星空下的拥抱 2024-11-22 10:11:09

try { ... } catch { ... } 不是内置函数(因为它是由模块提供的)。在 perl 5 中,这意味着您必须以分号结尾,如下所示:

try {
    $f = Foo->new(x => 'x');
} catch {
    die "oops\n";
};
print $f->x . "\n";

我无法回答 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:

try {
    $f = Foo->new(x => 'x');
} catch {
    die "oops\n";
};
print $f->x . "\n";

I can't answer how TryCatch manages to handle the missing semicolon - but it is possible using various black magic :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文