3

I'm trying to use an array of arrays in a Perl object and am still not getting how it works.

Here is the constructor:

sub new {
  my $class = shift;
  my $self = {};
  $self->{AoA} = [];
  bless($self, $class);
  return $self;
}

And here is the part of code which inserts stuff into AoA:

push (@{$self->{AoA}}[$row], $stuff);

I still can't find anything on the way to define an array of arrays in the constructor.

1 Answer 1

5

You don't need to define AoA in a constructor - merely the topmost arrayref. As far as the blessed hash is concerned, the AoA is merely an arrayref.

Your constructor is perfect.

To insert, you do 2 things:

# Make sure the row exists as an arrayref:
$self->{AoA}->[$row] ||= []; # initialize to empty array reference if not there.
# Add to existing row:
push @{ $self->{AoA}->[$row] }, $stuff;

Or, if you are adding a known-index element, simply

$self->{AoA}->[$row]->[$column] = $stuff;

Your problem with doing push @{$self->{AoA}}[$row] was that you dereferenced the array 1 level too early.

Sign up to request clarification or add additional context in comments.

2 Comments

Then what do I need to do besides pushing stuff in one of the arrays? Or am I pushing the wrong way?
@claferri - updated, please check if this answers. Sorry, saved too early

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.