blazar has asked for the wisdom of the Perl Monks concerning the following question:
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...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Instance data inheritance?
by merlyn (Sage) on May 13, 2005 at 11:28 UTC | |
|
Re: Instance data inheritance?
by tphyahoo (Vicar) on May 13, 2005 at 11:51 UTC | |
by blazar (Canon) on May 13, 2005 at 12:54 UTC | |
|
Re: Instance data inheritance?
by tlm (Prior) on May 13, 2005 at 22:16 UTC | |
|
Re: Instance data inheritance?
by Anonymous Monk on May 13, 2005 at 16:29 UTC | |
|
Re: Instance data inheritance?
by herveus (Prior) on May 16, 2005 at 11:25 UTC | |
by merlyn (Sage) on May 16, 2005 at 14:13 UTC | |
by blazar (Canon) on May 17, 2005 at 07:41 UTC | |
by herveus (Prior) on May 17, 2005 at 10:40 UTC | |
by blazar (Canon) on May 17, 2005 at 14:04 UTC |