Perl中双冒号和箭头的区别

时间:2019-12-23 10:24:06

标签: perl

如果重复,请说。我还没有找到它,仅适用于PHP,但适用于Perl。所以如果我可以写例如的全名GENERATED ALWAYS ASClass::sub(),我可以写$Class::scalarClass->sub(如果$Class->scalaruse d或require d ),perl的主要区别是什么?

问题是: Class Animal.pm:

Class

然后上Horse.pm类:

#!/usr/bin/perl -w
package Animal;
our $VERSION = '0.01';
sub speak {
    my $class = shift;
    print "a $class goes ", $class->sound;
}
sub sound{
    die "You have to defined sound() in a subclass";
}

如果我在主程序中这样做:

#!/usr/bin/perl -w
package Horse;
use Animal;
our @ISA = qw[Animal];
our $VERSION = '0.01';
sub sound { 'neight' }
1

输出----> #!/usr/bin/perl -w BEGIN{ unshift @INC, 'dirWithModules' } use Horse; use Animal;use Cow; Animal::speak('Horse'); 但是如果我可以

"a Horse goes neight"

输出---> #!/usr/bin/perl -w BEGIN{ unshift @INC, 'dirWithModules' } use Horse; use Animal;use Cow; Animal->speak('Horse')

所以我的问题是,如果我引用"You have to defined sound() in a subclass at Animal.pm"的类Horse.pm继承了speak的子类Animal.pm的方法,并以::,双冒号表示“没有问题”,它将打印声音。但是,如果我尝试使用->箭头引用该子项,则$class不会继承-也就是说,$class本身就是Animal.pm,但不是作为发送的参数({{ 1}})。那么'Horse'::有什么不同?

1 个答案:

答案 0 :(得分:5)

Foo->bar()是一个方法调用。

  • 必要时它将使用继承。
  • 它将传递请求者(->的左侧)作为第一个参数。因此,bar应该写为:

    # Class method (Foo->bar)
    sub bar {
       my ($class, ...) = @_;
    }
    

    # Object method (my $foo = Foo->new; $foo->bar)
    sub bar {
       my ($self, ...) = @_;
    }
    

Foo::bar()是子通话。

  • 它不会使用继承。