我需要爲Moose類實例添加屬性。在下面的代碼中,當我創建類Child的實例並向其添加屬性「app」時,我發現在創建下一個實例時也添加了此屬性。我做錯了,我需要每個創建實例的屬性。Perl Moose添加實例屬性無類屬性
#!C:\perl\bin\perl.exe
#!/usr/bin/perl
use v5.10;
use Moose;
use Data::Dumper;
{
package Child;
use Moose;
use utf8;
sub name {
say "My name is Richard";
}
}
sub add_attribute {
my ($object, $attr) = @_;
my $meta = $object->meta;
if (!$object->can("app")) {
$meta->add_attribute(app => (is => 'rw', default => sub{$attr}));
$object->app($attr);
}
else {
#$object->app($attr);
say "attr $attr already exists: object=". ref($object) . ", attr=".($object->app);
}
}
my $child = Child->new;
$child->name;
add_attribute($child, "First");
say "Child Attr: " . $child->app;
say "";
say Dumper($child);
my $child1 = Child->new;
$child1->name;
#add_attribute($child1, "Second");
say "Child1 Attr: " . $child1->app;
say Dumper($child1);
#say Dumper($child1->meta);
輸出:
My name is Richard
Child Attr: First
$VAR1 = bless({
'app' => 'First'
}, 'Child');
My name is Richard
Child1 Attr: First
$VAR1 = bless({
'app' => 'First'
}, 'Child');
你打算如何在實例上創建方法?在基於類的對象系統中,這意味着什麼? – 2014-10-12 13:02:26
據我所知,Moose屬性存儲在對象實例的哈希中,所以如果我在第一個實例中添加一個屬性,爲什麼這個屬性也存在於下一個創建的實例中,這個問題呢?我的問題現在清楚了嗎? – daliaessam 2014-10-12 13:09:56