Hi guys,
here is my problem:
You have a class, say, called Animal. Animal has a feature called DNA, and DNA is an array. Example:
package Animal; # constructor sub new { my $this = {}; # object properties $this->{DNA} = []; bless $this; return $this; } sub getDNA { my $this = shift; return "@{$this->{DNA}}"; } sub setDNA { my $this = shift; @{$this->{DNA}} = @_; return @{$this->{DNA}}; }
Now, imagine you want to create another class, say, called Population. And you want a bag of Animals, like:
package Population; use Animal; # constructor sub new { my $this = {}; # object properties $this->{individual} = []; bless $this; return $this; } sub init { for ($i=0; $i<5; $i++) { my $empl = Animal->new(); $empl->setDNA(4, 6, 8, 10); push (@{$this->{individual}}, $empl); } }
As you can see, the method init simply pushes 5 not empty Animals into a Population object.
The problem is that I'm not able to access them! What I should do if I want, say, set the DNA of a specific Animal of the Population?
And what if want to get or set a specific value of a specific slot of the DNA of an Animal...? I lack the knowledge I need. I tryied in many ways. Just an example, if I want to get the DNA of the Animal in the first slot:
sub getTheFirst{ my $this = shift; return @{$this->{individual}}[0]->getDNA(); }
But of course it's not working.
I can't get what I want...

In reply to arrays of object in OO perl by IL_MARO

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.