I would like to have a class, say MyClass each instance object of which holds some data, and having a method, say item really returning an object of another class, e.g. MyClass::Item. Now I want the latter to have access both to its specific data and to the instance data of the MyClass object.
I was thinking of a naive solution based on simply passing info about MyClass's specific instance to MyClass::Item 's constructor, a' la:
(example trimmed down to a bare minimum.)
#!/usr/bin/perl -l use strict; use warnings; package MyClass; sub new { my ($class, $data)=@_; bless { DATA => $data }, $class; } sub item { my $self=shift; MyClass::Item->new($self,@_); } package MyClass::Item; sub new { my ($class, $daddy, $data)=@_; bless { DADDY => $daddy, DATA => $data }, $class; } sub info { my $self=shift; "Generic data: ", $self->{DADDY}{DATA}, " - ", "This item's data: ", $self->{DATA}; } package main; my $c=MyClass->new('Foo'); my @items=map $c->item($_), qw/aa bb cc/; print $_->info for @items; __END__
However I strongly suspect that there may be better ways...
In reply to Instance data inheritance? by blazar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |