[Israel.pm] OO in perl question

Gaal Yahas gaal at forum2.org
Thu Nov 4 01:14:41 PST 2004

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>

More information about the Perl mailing list