Search code examples
arraysperlperl-data-structures

Array of arrays in a Perl object


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.


Solution

  • 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.