Re: Arrow dereference operator question



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
.



Relevant Pages

  • Re: Arrow dereference operator question
    ... array and list contexts. ... > sub mysub { ... Lists are not multidimensional. ... don't use &mysub unless you know why you are doing it, ...
    (perl.beginners)
  • Re: Multiple OUs?
    ... something is up with adding multiple values to the array... ... ' If the AD enumeration runs into an OU object, call the Sub again to ... strLine = Trim ... strNewContents = strNewContents & strLine & vbCrLf ...
    (microsoft.public.scripting.vbscript)
  • Re: Packages and returning errors
    ... > array intact. ... sub is_a_instance_method { ... my $class = shift; ... You need to fix the scope of $error by moving its declaration outside ...
    (comp.lang.perl.misc)
  • Classes and Arrays
    ... have created a class called "record" to store information about a folder and ... The Perms property is a dynamic array as per ... Each element in the Perms array should be another class called PermRec. ... Private Sub Class_Initialize ...
    (microsoft.public.scripting.vbscript)
  • Menue-Auswahl auf Kommandozeile
    ... Als Argument wird die Liste/Array übergeben, aus der ein Eintrag ausgewählt werden soll. ... Bei jeder Benutzung von readlist wird das Resultat abhängig von der übergebenen Argumentliste in einem Array gespeichert. ... Durch getrennte Queues werden mit den Pfeiltasten keine nicht in der Argumentliste enthaltenen Einträge angezeigt. ... sub readlist ...
    (de.comp.lang.perl.misc)