Is there way to catch the event of calling an instance of a Perl class?
my $obj = ExampleClass->new();
$obj(); # do something without producing error
I would like to be able to handle this from within the class/module definition. Something similar to the __call__
method in Python, or the __call
metamethod in Lua.
What you're looking for is called a functor. You can create a base class to implement your functors more easily. For instance:
Then, you can implement your functors as follows:
And finally, you can call the functor as follows:
Result will be:
I'm still not sure what the use case is, but you can
overload
the class to handle code dereferencing.Typical output:
Overloading "
&{}
" is obviously the way to go, but you could base your object on a sub instead of the commonly-preferred hash.ExampleClass.pm
:The main program:
Output:
This is basically what's called an "inside-out" object.