This must be very common/standard OO machinery, but it seems that only at an extremely slow pace can I grasp object oriented concepts and techniques.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.