使Perl对象可调用?

时间:2017-07-26 14:30:19

标签: perl

在Perl 5中,有没有办法让一个对象可以调用?

Example.pm

package Example;
use strict;
use warnings;
sub new {
    my ($class) = @_;
    my $self = {};
    bless($self, $class);
    return $self;
}

# implement function to make class callable

1;

main.pl

use Example;
my $ex = Example->new();
my $ex(); # call the object like this

1 个答案:

答案 0 :(得分:3)

这可以通过祝福函数引用而不是哈希引用来创建类来完成。

例如:

<强> Example.pm:

package Example;
use strict;
use warnings;
sub new {
    my ($class) = @_;
    my $self = \&call;
    bless($self, $class);
    return $self;
}

# implement function to make class callable
sub call {
    print "Calling the function\n";
}

1;

<强> main.pl:

use strict;
use warnings;
use Example;

my $ex = Example->new();
$ex->();

<强>输出:

  

调用函数