开发者

Odd behavior with Moose, Try::Tiny, and TryCatch

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?


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.


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜