Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
...And I get:use strict; use warnings; my $parent = Node->new('Parent'); my $child = Node->new('Child'); # this DWIM... (prints 'Parent') print $child->set_parent($parent)->get_parent->get_name, "\n"; # ...but $child is now undef, (Can't call method ... ) $child->set_name('New name'); print $child->get_name, "\n"; ################################# package Node; use Inline C => q{ typedef struct { char* name; double branch_length; struct Node* parent; struct Node* previous_sister; struct Node* next_sister; struct Node* first_daughter; struct Node* last_daughter; } Node; SV* new(char* class, char* name) { Node* node = malloc(sizeof(Node)); SV* obj_ref = newSViv(0); SV* obj = newSVrv(obj_ref, class); node->name = strdup(name); sv_setiv(obj, (IV)node); SvREADONLY_on(obj); return obj_ref; } SV* set_name(SV* self, char* name) { ((Node*)SvIV(SvRV(self)))->name = strdup(name); return self; } char* get_name(SV* self) { return ((Node*)SvIV(SvRV(self)))->name; } SV* set_parent(SV* self, SV* parent) { ((Node*)SvIV(SvRV(self)))->parent = parent; return self; } SV* get_parent(SV* self) { return ((Node*)SvIV(SvRV(self)))->parent; } void DESTROY(SV* self) { Node* node = (Node*)SvIV(SvRV(self)); free(node->name); free(node); } };
So what is the correct way to return self so it doesn't turn into undef?% perl inline.pl Parent Can't call method "get_name" on an undefined value at inline.pl line 1 +0.
|
|---|