Search code examples
functionperlclasscallinstance

Perl - call an instance of a class


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.


Solution

  • I'm still not sure what the use case is, but you can overload the class to handle code dereferencing.

    package ExampleClass;
    use overload '&{}' => \&__call__;   # Or an anon sub.
    sub new {
       bless {@_}, shift;
    }
    sub __call__ {
        sub { warn "calling an instance event" };
    }
    
    package main;
    my $obj = ExampleClass->new;
    $obj->();
    &$obj();      # same as $obj->()
    

    Typical output:

    $ perl 44956235.pl
    calling an instance event at 44956235.pl line 7.
    calling an instance event at 44956235.pl line 7.