Search code examples
arraysperl

Perl multidimensional array access


Lets say the multidimensional array is like this,

$myarray = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]];

Trying to access it in three ways,

print $myarray->[1][1] #prints 5
print $myarray->[1]->[1] #also prints 5
print $myarray[1][1] #prints nothing

I can't figure the difference between the first and the second type of access. Specifically, second one is more explicit but still first one works. That compels me to think third better work as well (which I know won't because myarray is actually a reference and not an array).


Solution

  • Three points

    1. $myarray is holding an array reference, not an array.
    2. $myarray and @myarray are different variables
    3. Perl doesn't really do multidimensional arrays

    All references are held in scalars, so all references are held in variables that start with $.

    The [ ... ] creates an anonymous array reference so [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] is creating an anonymous array reference containing 3 anonymous array references each containing 3 scalars.

    This means that the assignment to $myarray is assigning the outer anonymous array reference to it.

    In order two access what a reference is pointing two you need to dereference it. You can do that by placing the symbol for the type of what the reference points to in front of the reference like @$myarray. So $$myarray[0] is the first element of the anonymous array held in the reference $myarray or you can use the indirect syntax $myarray->[0].

    In your example $myarray->[0] holds the array reference [1,2,3] So this can be dereferenced in the same way giving $myarray->[0]->[0] This says dereference $myarray and give me the first element, which is an array reference, then dereference that and give me the first element of that.

    This gives your second example.

    Perl allows you to drop the -> between ] and [ as well as } and { for anonymous hashes, as syntactic sugar. This gives $myarray->[0][0] which is your first example.

    Your third example is looking for the first element of @myarray which is a different variable than $myarray. if you had put use strict at the top of your script Perl would have caught this error for you.

    It is a good idea to put

    use strict;
    use warnings;
    

    As the first two lines of any Perl script or module as they will trap a multitude of bad and potentially fatal errors in your Program. If you are debugging a program then adding use diagnostics under use strict gives more verbose messages.