Question

Syntactically, why doesn't the following code work? Suppose mySub() is a subroutine which returns two array references:

...
my @list1 = @{${mySub()}[0]};
my @list2 = @{${mySub()}[1]};
...

sub mySub{
    ...
    return \@array1, \@array2;
}

(Never mind the fact that I'm running this sub twice.) To my understanding, the curly braces tell perl that I want the output to be interpreted as an array, from which I extract the first (second) value and dereference it into an array.

Was it helpful?

Solution

Your:

@{${mySub()}[1]}

is placing the mySub() in a ${ ... }[ ... ], which expects an array reference to look up an element of, as if you had returned [ \@array1, \@array2 ] from your subroutine. You can find some helpful hints to think about how to deal with data structure references at http://perlmonks.org/?node=References+quick+reference.

In your case, you want to use a list slice, not an array element lookup, to get the arrayref you want to then dereference:

@{ ( mySub() )[1] }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top