How can I export a function with Moose::Exporter?

1.2k Views Asked by At

I wanted to export a simple function from a base class that I use all over my sub classes without having to use $self->myfunc() all the time, just a simple func() call.

I tried doing this with the example from Moose::Exporter

but I didnt understand what

as_is     => [ 'sugar3', \&Some::Random::thing ],

was doing, as the example seems incomplete. sugar3 isnt defined anywhere, so I dunno where or how to use it. Can I call sugar3() in the subclass now? Is sugar3() some secret Moose thing?

and then the was this thing... literally

thing;

that was exported, but I have no idea what thing is doing since there is no example of it. Is this a function call?

Anyway, more to the point how do you export functions like you would normally do with Exporter, but with Moose Exporter instead, and what happens if my baseclass has 3 levels of inheritance after it, will all the sub sub classes have access to this exported function?

1

There are 1 best solutions below

2
On BEST ANSWER

as_is => [ ... ]:

This list of function names or sub references will be exported as-is. You can identify a subroutine by reference, which is handy to re-export some other module's functions directly by reference (\&Some::Package::function).

sugar3 is the name of a sub to export.

Yes, you can call sugar3 in the subclass now if that's where you exported it to. That said, it's usually weird to export (anything but constants) to a subclass.

Yes, thing; is a sub call. Under no strict;, it could also be the same as 'thing';.

The sub classes won't have access to the sub unless it's called as a method (e.g. $o->thing; instead of thing;). It's extremely weird to export methods, though. Create a Moose::Role to give methods to a class.