Re: How to initialize class data?




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...
}

.



Relevant Pages

  • Re: Constructor equivalent
    ... ...since f hasn't been initialized in any way, ... So I need an pre-initializer as well. ... way then just looping through each element and initialize it with a ...
    (comp.lang.c)
  • Re: class variables: scoping
    ... instances of Foo is exemplified in the following code: ... >>But it should have method scope, ... (static data members in function body) ... need have boolean variables called initialize which act as follows. ...
    (comp.lang.cpp)
  • Re: hiding an interface (VB6)
    ... >I didn't notice a check in your Init() to see if it had already been ... >> the object when you initialize it, you could do something like the ... >> ByVal bData3 As Boolean) As Boolean ... >> Public Property Get Data1As String ...
    (microsoft.public.vb.general.discussion)
  • Re: How is member initialisation ordered?
    ... What happens when members have non-trivial ... > class MyClass ... > Foo foo; ... turn is used to initialize bar. ...
    (comp.lang.cpp)
  • Re: Atyfb questions and issues
    ... Then if the BIOS do the init, ... If it ends with 0x95, the chip has not been initialized, ... > otherwise I initialize it. ... clocked for DLLCLK and that kind of clocks, ...
    (Linux-Kernel)