【问题标题】:Make a Perl object callable? [duplicate]使 Perl 对象可调用? [复制]
【发布时间】:2017-07-26 14:30:18
【问题描述】:

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

ma​​in.pl

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

【问题讨论】:

    标签: perl


    【解决方案1】:

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

    例如:

    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;
    

    ma​​in.pl:

    use strict;
    use warnings;
    use Example;
    
    my $ex = Example->new();
    $ex->();
    

    输出:

    调用函数

    【讨论】:

    • 谢谢!有没有办法简单地用$ex()而不是$ex->()调用$ex
    • 我不这么认为。据我所知,类始终作为引用存储,因此您需要使用取消引用运算符-> 才能访问类数据。
    • 或者你可以做&$ex(),但我不认为这看起来更好恕我直言,并且假设 $ex 是一个函数参考。
    • @tjwrona1992,您的 new 始终返回相同的对象。另外,您没有解释如何为您的对象赋予属性,这完全是complicated
    • @aoiee, Re "有没有办法简单地用$ex() 调用$ex 而不是$ex->()",您可以阅读$ex调用一个 sub,但是您将无法将参数传递给 sub,并且您将无法将对象分配给任何其他 var。 /// $ex() 不是子调用;它甚至不是有效的 Perl 语法。 /// 你可以让$$ex 调用一个sub,但是你不能给sub 传递参数。
    猜你喜欢
    • 2011-09-21
    • 2017-02-11
    • 2019-08-10
    • 2020-08-26
    • 1970-01-01
    • 2021-07-29
    • 2012-11-18
    • 2012-06-26
    • 1970-01-01
    相关资源
    最近更新 更多