Perl - call an instance of a class

Viewed 731

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.

3 Answers

What you're looking for is called a functor. You can create a base class to implement your functors more easily. For instance:

package AbstractFunctorObject;
use strict;
use warnings;
use overload '&{}' => sub { $_[0]->can( '__invoke' ) };

sub new
{
  my $class = shift;
  bless { @_ }, $class;
}

1;
__END__

Then, you can implement your functors as follows:

package FunctorObject;
use strict;
use warnings;
use parent 'AbstractFunctorObject';

sub __invoke
{
  print "Called as a functor with args: @{ [ @_ ? @_ : 'no argument given' ] }\n";
}

1;
__END__

And finally, you can call the functor as follows:

package main;
use FunctorObject;

my $functor = FunctorObject->new();
$functor->('firstname', 'lastname');
$functor->();

Result will be:

root@jessie:/usr/local/src# perl callable_object.pl 
Called as a functor with args: firstname lastname
Called as a functor with args: no argument given
Related