Dmitry R
Dmitry R

Reputation: 3176

Perl - Array of objects in object

I have objA which has some level of abstraction, and I'm trying to create objB that has it's own attributes but one of them is array of objA. I want to be able to create objB and populate it's array of objA with values. How this can be coded in perl?

Upvotes: 0

Views: 177

Answers (1)

Borodin
Borodin

Reputation: 126722

If your ObjA objects are based on hashes then you can have a field that corresponds to an array reference to store the list of ObjB objects.

You don't say how you want to use or access these items, but you could, say, write your methods like this

package ObjA;

sub new {
  my ($class);
  bless {}, $class;
}

sub add_b_object {
  my ($self, $b_obj);
  push @{ $self->{b_objects} }, $b_obj;
}

Then your code would look like

my $a_obj = ObjA->new;

for (1..3) {
  my $b_obj = ObjB->new;
  $a_obj->add_b_object($b_obj);
}

I hope that helps

Upvotes: 2

Related Questions