Perl Moose add instance attribute not class attribute -



Perl Moose add instance attribute not class attribute -

i need add together attribute moose class instance. in code below, when create instance of class kid , add together attribute "app" it, find attribute added when create next instances. doing wrong, 1 time again need attribute per created instance.

#!c:\perl\bin\perl.exe #!/usr/bin/perl utilize v5.10; utilize moose; utilize data::dumper; { bundle child; utilize moose; utilize utf8; sub name { "my name richard"; } } sub add_attribute { ($object, $attr) = @_; $meta = $object->meta; if (!$object->can("app")) { $meta->add_attribute(app => (is => 'rw', default => sub{$attr})); $object->app($attr); } else { #$object->app($attr); "attr $attr exists: object=". ref($object) . ", attr=".($object->app); } } $child = child->new; $child->name; add_attribute($child, "first"); "child attr: " . $child->app; ""; dumper($child); $child1 = child->new; $child1->name; #add_attribute($child1, "second"); "child1 attr: " . $child1->app; dumper($child1); #say dumper($child1->meta);

output:

my name richard kid attr: first $var1 = bless( { 'app' => 'first' }, 'child' ); name richard child1 attr: first $var1 = bless( { 'app' => 'first' }, 'child' );

the trick create new subclass of original class, add together attribute that, rebless instance new subclass. here's example:

use v5.14; bundle person { utilize moose; has name => (is => 'ro'); } sub add_attribute { ($obj, $name, $value) = @_; $new_class = moose::meta::class->create_anon_class( superclasses => [ ref($obj) ], ); $new_class->add_attribute($name, => 'rw'); $new_class->rebless_instance($obj, $name => $value); } $alice = person->new(name => 'alice'); $bob = person->new(name => 'bob'); add_attribute($alice, foot_size => 6); $alice->foot_size; $bob->foot_size; # dies, no such method

perl moose

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -