我刚开始与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
是正确的值,例如5
,Try::Tiny
仍然会产生undefined value
错误。由于我一直在阅读的所有Moose文档都使用
Try::Tiny
,所以我对为什么此代码无法正常工作感到非常困惑。我在这里做错什么吗? 最佳答案
Try::Tiny
在try/catch节的结尾需要一个分号:
try {
$f = Foo->new(x => 'x');
} catch {
die "oops\n";
};
这是由于
Try::Tiny
的实现-try
和catch
都是函数。关于perl - Moose,Try::Tiny和TryCatch的奇怪行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6365829/