in reply to Access package variables of subclass from base class

Write a an accessor in each child class, like this:
#!/usr/bin/perl use strict; use warnings; { package Parent; sub f { my $self = shift; $self->classvar += 5; } } { package Child; our @ISA = qw(Parent); our $classvar = 3; sub classvar :lvalue { $classvar; } } my $obj = bless {}, 'Child'; $obj->f(); print $Child::classvar, $/; # output: 8

Here the method f in the parent class accesses the method classvar in the child.

If you only want to allow read access, you can leave out the :lvalue attribute.

Replies are listed 'Best First'.
Re^2: Access package variables of subclass from base class
by slower (Acolyte) on Mar 05, 2009 at 16:18 UTC
    Thanks moritz, this looks like the cleanest solution. I didn't know about the :lvalue attribute -- that's quite handy. Sure beats what I was doing for accessors/mutators before:
    sub classvar { my $self = shift; $self->{classvar} = shift if @_; return $self->{classvar}; }