Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Static Variables in Perl

by friedo (Prior)
on Mar 30, 2006 at 20:24 UTC ( [id://540268]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://540268]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-03-28 23:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found