[Israel.pm] OO in perl question

Gaal Yahas gaal at forum2.org
Thu Nov 4 03:01:58 PST 2004


On Thu, Nov 04, 2004 at 11:53:33AM +0200, Itamar Elem wrote:

> > > 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.

> 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

Why don't you try and see?

Okay, I don't feel like baiting. You need to turn off strict 'refs' in
the place where you do it.

But before you proceed, make sure you understand the difference between
object (instance) data, and class ("static") data. I have a feeling you
just need a regular inherited field, in which case Class::Accessor will
do what you want.

In any case, in Perl you don't need a package to explicitly 'use' another
package to access its globals. If that package has already been loaded,
fully qualified access works. (If it hadn't been loaded yet, the access
"works" too, in the sense that your read attempts autovivify the unloaded
package and return undef; and that writes will in fact update that
package's namespace.)

-- 
Gaal Yahas <gaal at forum2.org>
http://gaal.livejournal.com/



More information about the Perl mailing list