Search code examples
perlmoose

Initializing a CodeRef field of a Moose class


I have a Moose class Person

 package Person;

  use Moose;

  has 'first_name' => (
      is  => 'rw',
      isa => 'Str',
  );

  has 'last_name' => (
      is  => 'rw', 
      isa => 'Str',
  );

  has 'check' => (
      is => 'rw',
      isa => 'CodeRef',
  );

  no Moose;
  __PACKAGE__->meta->make_immutable;

I am initializing a new Person object in another file like so

use Person;

my $user = Person->new(
    first_name => 'Example',
    last_name  => 'User',
    check => sub {
        print "yo yo\n";
    },
  ); 

print "here\n";
$user->check();
print "here\n";

The two here debug statements are printing but the debug message in the subroutine is not.

I'd like to know the correct way for me to pass a function to the constructor such that I can pass an anonymous sub routine to the object.


Solution

  • $user->check() is equivalent to $user->check. It just returns the value of the check attribute (i.e, the coderef) without doing anything with it -- just like any other accessor would. The fact that this attribute holds a coderef doesn't change that.

    If you want to retrieve the coderef, then call it, you need another arrow:

    $user->check->()