Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

How do I create static class variables (class data)?

by btrott (Parson)
on Apr 21, 2000 at 03:37 UTC ( [id://8299]=perlquestion: print w/replies, xml ) Need Help??

btrott has asked for the wisdom of the Perl Monks concerning the following question:

Replies are listed 'Best First'.
Re: How do I create static class variables (class data)?
by btrott (Parson) on Apr 21, 2000 at 03:38 UTC
    Perl doesn't have a special syntax for creating such variables. All you have to do, basically, is declare a lexical variable at the start of the file in which you're declaring your class, like
    package Foo; my $Bar = 0;
    It's important to declare it with my rather than as a package global, because the latter could be accessed directly by scripts using your class--and you don't want that (well, most likely you don't).

    You shouldn't just use this variable directly in your class, though, because your class won't be very inheritable. Subclasses that inherit your methods will be altering *your* class variable rather than their own; you don't want this.

    To fix this, take a reference to the data and store it in your objects. For example, say that you have an object that's really a hash reference--to give it access to your class data, you could do this:

    $self->{'_BAR'} = \$Bar;
    in your constructor. When you want to access the class data, then, just use it like you would a regular reference:
    print "\$Bar is currently ", ${ $self->{'_BAR'} };
    And there you go! Your very own static member.

    For more information and for some practical uses of such a variable, take a look at perltoot.

Re: How do I create static class variables (class data)?
by chromatic (Archbishop) on Apr 21, 2000 at 04:17 UTC
    The new keyword our (introduced in Perl 5.6) provides a package scope for variables. It is demonstrated in perltootc.

Log In?
Username:
Password:

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

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

    No recent polls found