in reply to How do I create static class variables (class data)?
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).package Foo; my $Bar = 0;
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:
in your constructor. When you want to access the class data, then, just use it like you would a regular reference:$self->{'_BAR'} = \$Bar;
And there you go! Your very own static member.print "\$Bar is currently ", ${ $self->{'_BAR'} };
For more information and for some practical uses of such a variable, take a look at perltoot.
|
|---|