perl - Moose,Try::Tiny和TryCatch的奇怪行为

标签 perl moose

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

相关文章:

perl - 使用 Moose 的 before 更改方法参数与隐私冲突

apache - 如何使用带有 Bitnami LAMP Stack 的 mozilla 执行脚本 Perl?

perl - 为什么通过 Perl Socket->send() 的 sendto() 忽略对等地址?

perl - MooseX::类型和强制错误

perl - 在 Moose 中,如何在定义多个属性时声明谓词和更清晰的方法?

perl - 为什么带有方法修饰符的 Moose 角色应用程序在我的代码中不起作用?

perl - Perl 中 BEGIN block 的作用是什么?

perl - __PACKAGE__->{foo} 是什么意思?

mysql - perl lwp useragent和mysql数据下载和更新字符集麻烦

perl - 如何覆盖 Moose::Role 中的 sub?