perlconstructormoose

How can I rename the default constructor provided by Perl's Moose module?


Is there a way to rename the default constructor provided by Moose to something other than "new"?

I want to do this to make a script more user friendly when it would make more sense to name the constructor something different (like "make_thing" for example)

my $object = Class->make_thing();

How can I make this happen?


Let me give you an example of how this might be more user friendly...

Say I'm building a module that handles CVS repository information and the module is called "CVS". I could either create an instance of a repository with

$repository = CVS->new()

or if I could change the name of the constructor I could call it something like

$repository = CVS->get_repository()

which would make more logical sense the user.


Solution

  • Sometimes it makes sense to have alternative constructors. For instance, if you look at Net::Works::Network, it has new_from_string and new_from_integer methods. I'd stay away from using something other than new unless you have a very good reason. Having said that, you could just add a convenience method if you think it's more helpful to the user.

    sub get_repository {
        my $class = shift;
        return $class->new( @_ );
    }