On 20 Jun 2001 11:28:58 -0500, Nick Transier wrote:
> I have two different packages that access each others methods. (where in my 
> case one package is an element I have defined and the other package is an 
> implementation of a list of those elements) When I call a method from 
> package 1 with an object from package 2. the method in package 1 takes a 
> $self var as the first parameter. This much I believe I 
> understand...However, does that $self var then allow you to access all of 
> the methods of it's originial package (2), or do have to make some sort of 
> package definition?
> 
> Thanks,
> -Nick
> _________________________________________________________________
> Get your FREE download of MSN Explorer at http://explorer.msn.com
> 
> 

An object reference (ie the first argument of a method: $self) can only
access methods of its class and any classes it inheirited from (those
classes in its @ISA array).  Of course you could always call the method
with a reference to the Container object like this does:

#!/usr/bin/perl

use strict;

my $Holder = Container->new;

#add three Element objects to $Holder
$Holder->add(Element->new("Fred"));
$Holder->add(Element->new("Barney"));
$Holder->add(Element->new("Dino"));

$Holder->fiddle();

package Container;

#create me!
sub new { return bless {}, $_[0] }

#add an Element object to my interal array
sub add { push @{$_[0]->{'_array'}}, $_[1] }

#causes all of the Element objects in my array to say their name and 
#give info about me
sub fiddle {
        my $self = shift;

        foreach my $element (@{$self->{'_array'}}) {
                $element->print_info($self);
        }
}

#returns the number of objects in my array
sub num_of_objects_pointed_to { return scalar(@{$_[0]->{'_array'}}) }

package Element;

#create me!
sub new { return bless { '_name' => $_[1] }, $_[0] }

#print info about me and the Container that holds me
sub print_info {
        my ($self, $holder) = @_;

        print "my name is ", $self->{'_name'}, " and I am one of " .
              $holder->report_num_of_objects_pointed_to . " objects\n";
}

--
Today is Sweetmorn, the 25th day of Confusion in the YOLD 3167
Or is it?


Reply via email to