Search code examples
perlperl-data-structures

How can I dereference an array of arrays in Perl?


How do I dereference an array of arrays when passed to a function?

I am doing it like this:

my @a = {\@array1, \@array2, \@array3};

func(\@a);


func{
    @b = @_;

    @c = @{@b};
}

Actually I want the array @c should contain the addresses of @array1, @array2, and @array3.


Solution

  • my @a = {\@array1, \@array2, \@array3};
    

    The above is an array with a single member -> a hash containing:

    { ''.\@array1 => \@array2, ''.\@array3 => undef }
    

    Because as a key in the hash, Perl coerces the reference to @array1 into a string. And Perl allows a scalar hash reference to be assigned to an array, because it is "understood" that you want an array with the first element being the scalar you assigned to it.

    You create an array of arrays, like so:

    my @a = (\@array1, \@array2, \@array3);
    

    And then in your function you would unpack them, like so:

    sub func {
        my $ref = shift;
        foreach my $arr ( @$ref ) {
            my @list_of_values = @$arr;
        }
    }
    

    Or some variation thereof, like say a map would be the easiest expression:

    my @list_of_entries = map { @$_ } @$ref;
    

    In your example, @c as a list of addresses is simply the same thing as a properly constructed @a.