in reply to Complex Data Structures in Object Creation
package foo; sub new { my $class = shift; # Default initialization my $self = { 'some_scalar' => "", 'another_scalar' => "", 'some_array' => [], 'an_array_of_arrays' => [], # also }; # initialize $self from @_. # you may be calling package functions which expect to shift in a r +ef to data. bless $self, $class; }
Now methods can use $self to deal with the data.
Update: crazyinsomniac and chromatic have both objected to this. An instance of foo can provide itself with a name for the ref returned by bless. foo::bar() needs to shift in the instance from its first argument, that's standard. Why ever name something? I was assuming that the real constructor would find named data handy, as in setting up closures as class methods (e.g. accessors ala Class::Struct). If there is an implicit way of doing that on an anonymous ref, I'd enjoy learning it.
Update2: Added a couple of comments to code. How do you call a package function from the constructor without a named reference? A complex data struct will have special methods for dealing with its components, and some of them will be wanted in new(). In C++ you can't use object methods in a ctor, but perl is different.
After Compline,
Zaxo
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Complex Data Structures in Object Creation
by chromatic (Archbishop) on Jun 24, 2001 at 21:18 UTC |