By leaving your data structure anonymous, you lose the means of access to it. The fix is simple:

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


In reply to Re: Complex Data Structures in Object Creation by Zaxo
in thread Complex Data Structures in Object Creation by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.