Re: Arrow dereference operator question
- From: dunric29a@xxxxxxxxx (David Unric)
- Date: Thu, 31 May 2007 11:18:00 +0200
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 <chas.owens@xxxxxxxxx> wrote:
On 5/31/07, David Unric <dunric29a@xxxxxxxxx> 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 \@array;
}
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
- References:
- Arrow dereference operator question
- From: David Unric
- Re: Arrow dereference operator question
- From: Chas Owens
- Arrow dereference operator question
- Prev by Date: Re: Outlook CSV Parser
- Next by Date: did I get greedy quantifiers wrong ?
- Previous by thread: Re: Arrow dereference operator question
- Next by thread: did I get greedy quantifiers wrong ?
- Index(es):
Relevant Pages
|
|