I did suspected it would have something to do with the difference between
array and list contexts.
Your analysis seems to be correct.
Thank you for solving this puzzle :)
Regards
On 5/31/07, Chas Owens <[EMAIL PROTECTED]> wrote:
On 5/31/07, David Unric <[EMAIL PROTECTED]> wrote:
> Based on perlref documentation arrow operator between brackets
subscripts
> may be omitted so the following code is valid:
>
> @array = ( [1, 2], [3, 4] );
> $element = $array[0][0]; # shorthand for $element = $array[0]->[0]
>
>
> Could somebody explain why it causes syntax error when the above rule is
> applied to returned value of a subroutine ?
>
> sub mysub {
> @array = ( [1, 2], [3, 4] );
>
> return @array;
> }
>
> $element = (&mysub)[0][0]; # $elem = (&mysub)[0]->[0] is valid
> ------------------------------
> syntax error at testarr.pl line 7, near "]["
>
My best guess is that the problem here is that (mysub())* is a list
not an array. Lists are not multidimensional. Try
my $element = ([1, 2], [3, 4])[0][0];
Notice how it gets the same error?
The simple solution is to use the arrow, or have the sub return an
arrayref. Here are some ways to do it:
#!/usr/bin/perl
use strict;
use warnings;
sub list {
my @array = ( [1, 2], [3, 4] );
return @array;
}
sub aref {
my @array = ( [1, 2], [3, 4] );
return [EMAIL PROTECTED];
}
print (
(list())[0]->[0], "\n",
"${[list()]}[0][1]\n",
"${aref()}[1][0]\n",
(aref())->[1][1], "\n"
);
* don't use &mysub unless you know why you are doing it, use mysub()
instead