Re: How to initialize class data?



Ralph Moritz wrote:
I've got some class data which I want to initialize once.
I was thinking of doing it like this:

{ package Foo;

my $FirstTime = 1;

sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$class->init() if ($FirstTime);
}

sub init {
# Initialize class data...
$FirstTime = 0;
}
}

Is this okay, or is there a generally accepted way
to do this?

What do you mean by "class data" in this case? Variables scoped to the
package, that all class-methods and object-methods would have access
to? If that's the case, I have a dumb question - why aren't you just
declaring these variables to be initialized to whatever they need to be
initialized to?

That is, instead of:
{
package Foo;
my $FirstTime = 1;
my $data;

sub new {
#...
initialize_data() if $FirstTime;
}

sub initialize_data {
$data = "Stuff";
$FirstTime = 0;
}
}

why aren't you just doing:

{
package Foo;
my $data = "Stuff";

sub new {
#...
}
}

?

If I've over simplified things so as to remove the point of your
question, please give us a better idea of what it is you're trying to
accomplish.

Paul Lalli

.



Relevant Pages