Search code examples
perlmoose

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?


Solution

  • 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.