in reply to Static Variables in Perl

The best way to do this is probably to just inherit accessor and mutator methods, and not try to alter the class data directly.

package Parent; our $knob = 1; sub knob { my $class = shift; $knob = $_[0] if @_; return $knob; } package Child; use base 'Parent'; # inherits knob method

That way, calling Parent->knob or Child->knob will get and set the same package global in Parent. To make it safer, you could make $knob a lexical, so it's only visible via the method call.

Update: Better mutator code per Tanktalus's comment.

Replies are listed 'Best First'.
Re^2: Static Variables in Perl
by Tanktalus (Canon) on Mar 30, 2006 at 20:32 UTC

    Minor tweak:

    $knob = $_[0] if @_;
    That way, Parent->knob() is an accessor, while Parent->knob(undef) is a mutator that sets the $knob to undef. Slightly better:
    if (@_) { # check that $_[0] is allowed. $knob = $_[0]; }
    but that's only if there are invalid values you want to block.