[Israel.pm] OO in perl question

Itamar Elem elem at compugen.co.il
Thu Nov 4 01:53:33 PST 2004


gaal

when you suggest to do ${ ref($instance) . "::a" }
from inside B where b is the base class and lets say ref($instance)==D1
one of the derived class of B;
the base B dont do : use D1;(D1 do :use B)
anf get_a work from B package. is ${D1::a}  accessible  in that situation

thanks itamar

-----Original Message-----
From: Gaal Yahas [mailto:gaal at forum2.org]
Sent: Thursday, November 04, 2004 11:15 AM
To: Perl in Israel
Subject: Re: [Israel.pm] OO in perl question


On Thu, Nov 04, 2004 at 10:51:56AM +0200, Itamar Elem wrote:
> i have the following situation:
> packages D1,..,Dk which derived from package B in perl
> and var $a in each of the packages D1,..Dk, B
> 
> and lets say single accessor name get_a defined in B only;
> 
> is there clean way which get_a return the correct $a;
> 
> for example:
> 
> $c = new D2();
> 
> print $c->get_a()
> 
> will print the content of $a from D2;
> is there different sollution if $a is my var or global package var

Do you need class data, or instance data?

In any case, the first argument to get_a() will be a Dk instance. If
you want class data, ${ ref($instance) . "::a" } is how you access the
package global $Dk::a for an arbitrary k, and yes, you should be using
package globals and not lexical ("my") variables. If you want instance
data, it makes no sense to put the data in a package global, and the
instance has to be a reference to some per-instance data: typically a hash
(what does your constructor look like?). So get_a() should access $c->{a}
(and 'a' is neither a lexical OR a global, but rather a hash element).

If you want something to do this for you, look at Class::Data::Inheritable
and Class::Accessor from CPAN. The latter is for instance data.

-- 
Gaal Yahas <gaal at forum2.org>
http://gaal.livejournal.com/
_______________________________________________
Perl mailing list
Perl at perl.org.il
http://perl.org.il/mailman/listinfo/perl




More information about the Perl mailing list