perl - 使 Perl 对象可调用?

标签 perl

在 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;

ma​​in.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;

ma​​in.pl:

use strict;
use warnings;
use Example;

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

输出:

Calling the function

关于perl - 使 Perl 对象可调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45329936/

相关文章:

perl - 如何总结 perl 中线程数组返回的所有值?

perl - 按另一个列表中定义的顺序从哈希中获取值

perl - 在 Perl 中使用 Net::STOMP::Client 模块通过 SSL 连接到 JMS 主题代理时出错

java - 动态生成变量名

perl - 如何在 Windows 中通过 Perl 访问网络共享?

用 perl 替换正则表达式 EOL 会产生意想不到的结果

arrays - 比较两个数组并找出差异

Perl 为使用任意数量的模块和库的脚本生成一个可执行文件

perl - Perl Do-While 被认为是最佳实践(AKA 专业编码标准)还是应该使用替代方案?

linux在foreach循环a1,a2,a3中打印变量值