我刚开始与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.

但是,如果我将Try::Tiny替换为TryCatch,则其作用与我认为的应为:
oops

即使x是正确的值,例如5Try::Tiny仍然会产生undefined value错误。

由于我一直在阅读的所有Moose文档都使用Try::Tiny,所以我对为什么此代码无法正常工作感到非常困惑。我在这里做错什么吗?

最佳答案

Try::Tiny在try/catch节的结尾需要一个分号:

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

这是由于Try::Tiny的实现-trycatch都是函数。

关于perl - Moose,Try::Tiny和TryCatch的奇怪行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6365829/

10-14 15:04
查看更多