Accessing parent objects

C

Christoph Haas

Hi, group...

After hours of reading kilobytes of documentation I'm desperate enough
to bother you. :)

I have an object (child) created within another object (parent).
(See below for the "trivial" source code.) Methods of the parent package
can easily handle children objects like $parent->{'children'}. But is
there a way to do this vice-versa? Assume I'm a child and I want to know
what other children there are. I need a handle to "go up" the object
tree to check the parent object.

There are two possible solution I can think of:

a) Give each child a handle to its parents like
$parent->new_child($parent);
(This could break if the object is not a member of "parent"
and the children assume they have parent.)
b) Use global variables for children (then how do I access them
from inside of each package? can I "tie" them somehow and use
them simultaneously from every children object?)

What is the best way to handle this?

================================================
Parent.pm:
==========
package Parent;

use Child;

sub new
{
my $package = shift;
my $self = { };

my %children = ();
$self->{'children'} = \%children;

bless($self, $package);
return $self;
}

sub new_child
{
my $self = shift;
my $name = shift;
$self->{'children'}->{$name} = new Child;
}

=========
Child.pm:
=========
package Child;

sub new
{
my $package = shift;
my $self = { };

bless($self, $package);
return $self;
}
================================================

Thanks for your ideas...

Christoph
 
C

Christoph Haas

Update... (argh, Mozilla ate my first reply)

I just came across a nice tutorial on variable scopes at
http://perl.plover.com/FAQs/Namespaces.html.en#The_Current_Package
which describes very clearly how lexicals and packages work.

I'm now convinced that the best way is declaring global variables
in the main package and then just refer to them via $main::parent
(or short: $::parent) from within the "child" objects from the
"Child" package.

If other have fresh ideas - let me know.

Christoph
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,266
Messages
2,571,075
Members
48,772
Latest member
Backspace Studios

Latest Threads

Top