Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-03-29 07:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found