I've just begun designing a Perl class, and my only prior experience with OOP is with C++, a long time ago.
There are a few items of data that I need to be "class variables" - shared by all instances. I'd like for them to be initialized prior to the first time I instantiate an object, and I'd like for the main program that issues use MyClass
to be able to provide a parameter for that initialization process.
Here's a working example of a class with a class variable:
package MyClass;
use strict;
use warnings;
# class variable ('our' for package visibility)
#
our $class_variable = 3; # Would like to bind to a variable
sub new {
my $class = shift;
my $self = { };
bless $self, $class;
return $self;
}
sub method {
my $self = shift;
print "class_variable: $class_variable\n";
++$class_variable; # prove that other instances will see this change
}
And here's a demo:
#!/usr/bin/perl
use strict;
use warnings;
use MyClass;
my $foo = MyClass->new();
$foo->method(); # show the class variable, and increment it.
my $bar = MyClass->new();
$bar->method(); # this will show the incremented class variable.
Is there any way for the main program to specify a value for $class_variable? The value would be known at compile time in the main program.
Using the import facility:
Pass the value when you use the module:
It's not exactly idiomatic Perl, but it's not uncommon either. That sanity check in the middle of the function should give you a hint about why it might not be the best approach in all cases. If MyClass is only supposed to be
use
d from a top-level script, you could enforce that sanity check instead:You can also make the variable "private" by declaring it with
my
instead ofour
. In such a case, you have to provide a class method to initialize it:And then in the programme:
You can also use a Class method:
Ex:
In your script you'd invoke this by doing: