Perl Arrays of Arrays

Coming from the python background, this arrays of arrays in perl has given me so much pain. I decided to put down this cheat sheet here for future reference. Basic perl knowledge is assumed.

    # assign to our array, an array of array references
    @AoA = (
           [ "fred", "barney" ],
           [ "george", "jane", "elroy" ],
           [ "homer", "marge", "bart" ],
    print $AoA[2][2];

    # assign a reference to array of array references
    $ref_to_AoA = [
        [ "fred", "barney", "pebbles", "bambam", "dino", ],
        [ "homer", "bart", "marge", "maggie", ],
        [ "george", "jane", "elroy", "judy", ],
    print $ref_to_AoA->[2][2];

For @array, use parentheses, i.e. the top example. For a reference, use square brackets, i.e. the bottom example.

Example for populating an array:

my @array = ();
push @array, ["John Smith", 35];
push @array, ["Mary Brown", 27];

Notice the square brackets here. This is because we want to keep John and 35 as one entity, so we use the square brackets here to make a reference being pushed to the array. If we use the parentheses here it will be a disaster.

How to read the above?

foreach my $entity (@array){
  my $name = $entity->[0];
  my $age = $entity->[1];
  # do something...

If in python, it will be hecka easy. There is no worries about square brackets or parentheses, arrays or references. The mind can be fully devoted to the logic flow, instead of the language syntax.

L = []
L.append(["John", 35])
L.append(["Mary", 27])
for entity in L:
  name = entity[0]
  age = entity[1]
  print name + " : " + str(age)

There is more pain to this perl arrays of arrays thing… Learn more of it at:

Gosh, everyone should be using python, at least not perl.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s