Re: Arrow dereference operator question
- From: chas.owens@xxxxxxxxx (Chas Owens)
- Date: Thu, 31 May 2007 03:13:47 -0400
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
.
- Follow-Ups:
- Re: Arrow dereference operator question
- From: David Unric
- Re: Arrow dereference operator question
- References:
- Arrow dereference operator question
- From: David Unric
- Arrow dereference operator question
- Prev by Date: Arrow dereference operator question
- Next by Date: Re: Outlook CSV Parser
- Previous by thread: Arrow dereference operator question
- Next by thread: Re: Arrow dereference operator question
- Index(es):
Relevant Pages
|
|