Perl - call an instance of a class

前端 未结 3 1937
不思量自难忘°
不思量自难忘° 2020-12-20 19:29

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
         


        
3条回答
  •  清酒与你
    2020-12-20 20:03

    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
    

提交回复
热议问题