gpt4 book ai didi

perl - 为什么相同的函数调用在对象内部会带来不同的结果?

转载 作者:行者123 更新时间:2023-12-04 18:35:07 24 4
gpt4 key购买 nike

我正在使用 Moose::Meta::Class 动态添加类、方法和属性。

谁能解释为什么这段代码有效(在 Cat 类内部调用 generate() 子程序):

package Cat;

use Moose;

sub generate {

my $siberian = Moose::Meta::Class->create( 'Siberian' );
$siberian->add_method( echo => sub { print "yeah!\n" } );


my $tiger = Moose::Meta::Class->create( 'Tiger' );
$tiger->add_attribute(
Siberian => {
is => 'ro',
default => sub { $siberian->new_object; }
},
);

__PACKAGE__->meta->add_attribute(
Tiger => {
is => 'ro',
default => sub { $tiger->new_object },
},
);

print "Generation done!\n";
}

generate();


package main;

use Data::Printer;

my $a = Cat->new;

# $a->generate;
p( $a );
$a->Tiger->Siberian->echo; # returns 'yeah!'

p($a) 的输出:

Cat  {
Parents Moose::Object
public methods (3) : generate, meta, Tiger
private methods (0)
internals: {
Tiger Tiger
}
}

而这个(通过 $a->generate 从外部调用 generate sub)不会:

package Cat;
use Moose;

sub generate {

my $siberian = Moose::Meta::Class->create('Siberian');
$siberian->add_method(
echo => sub { print "yeah!\n" }
);

my $tiger = Moose::Meta::Class->create('Tiger');
$tiger->add_attribute(
Siberian => {
is => 'ro',
default => sub { $siberian->new_object; }
},
);

__PACKAGE__->meta->add_attribute(
Tiger => {
is => 'ro',
default => sub { $tiger->new_object },
},
);

print "Generation done!\n";

}

# generate();


package main;
use Data::Printer;

my $a = Cat->new;
$a->generate;
p($a);
$a->Tiger->Siberian->echo; # returns 'yeah!'

p($a) 的输出:

Cat  {
Parents Moose::Object
public methods (3) : generate, meta, Tiger
private methods (0)
internals: {}
}

程序返回错误:

Can't call method "Siberian" on an undefined value at base2.pl line 39.

最佳答案

由于generate不是对象,而是类方法,所以需要在new之前调用:

Cat->generate;
my $a = Cat->new;

关于perl - 为什么相同的函数调用在对象内部会带来不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43520984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com