在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
答案 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->();
<强>输出:强>
调用函数