Re: How to initialize class data?
- From: "Brian McCauley" <nobull67@xxxxxxxxx>
- Date: 27 Sep 2006 09:41:58 -0700
Ralph Moritz wrote:
Hi,
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?
The canonical way would be an INIT block.
Or sometimes you'll see people just not put the code in a subroutine at
all.
But both of these will make the initialization code be called even if
Foo is never instanciated.
If you really want to defer until the first object is instanciated then
what you are doing is approximately correct. However you should not be
calling $class->init() you should call Foo->init() or simply init().
With your code if the first Foo object that's instanciated happens to
be a of a subclass you'll call init() in that subclass.
Oh and it's probably more ideomatic to reverse the sense of your flag.
my $initialized;
sub init {
$initialized++; # Slower than =1 but the more common idiom
# etc...
}
sub new {
init unless $initialized;
my $class = shift;
my $self = bless {}, $class;
# etc...
}
.
- Prev by Date: Re: glob problem: escaped space seems to be significant too (was Re: Problem with glob and filenames containing '[' and ']')
- Next by Date: Re: How to dynamically generate function name and call it?
- Previous by thread: Re: How to initialize class data?
- Next by thread: Re: How to dynamically generate function name and call it?
- Index(es):
Relevant Pages
|