在 Perl 5 中,有没有办法使对象可调用?
示例.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
最佳答案
这可以通过使用函数引用而不是哈希引用来创建类来完成。
例如:
示例.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->();
输出:
Calling the function
关于perl - 使 Perl 对象可调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45329936/