Terry
Terry

Reputation: 1232

How can I get the nth element of a dereferenced anonymous array?

use strict;

my $anon = [1,3,5,7,9];
my $aref  = [\$anon];

print "3rd element: "  . $ { $aref } [2] . "\n";

I'd like to get the nth element of the anonymous array $anon over the $aref variable. In the code I wanted to get the 3rd element of $anon by making the index 2 but it returned nothing. If I write $ { $aref } [0] then it returns something like REF(0x7fd459027ac0)

How can I get the nth, for example the 3rd element of $anon ?

Rationale:

my @area = (
    qw[1 3 5 7 9],
    qw[2 4 6 8 0],
    qw[a e i u o],
    qw[b c d f g]
    );

foreach my $row (@area) {
    foreach my $cell (@$row)
    {
    # do some processing on the element
    print $cell . " ";
    }
    print "\n";
}

Upvotes: 2

Views: 1648

Answers (2)

mwp
mwp

Reputation: 8467

You have a classic list-of-lists data structure, with a twist. You need to fetch the first element of the outer array reference, given by $aref, dereference the result, and then fetch the nth element of the inner array reference returned by that expression. This should do the trick:

${ $aref->[0] }->[2]

You may want to read through perllol and possibly even perlref for more information and ideas. If you have control over this data structure, there are better ways to build it. For example, if it were built like so:

my $anon = [1, 3, 5, 7, 9]; # a reference to an anonymous array
my $aref = [$anon]; # a reference to an anonymous array containing only the above reference

You could simply do:

$aref->[0][2]

Upvotes: 1

Borodin
Borodin

Reputation: 126732

How can I get the nth element of a dereferenced anonymous array?

You have too many reference to operators. You have built a nested structure three levels deep and it's no wonder you're having trouble navigating it

The problem is that your $anon is already a reference to an anonymous array. Square brackets [...] construct an anonymous array and return a reference to it

You then have

my $aref  = [\$anon]

which creates another reference to an array with one element: a reference to the scalar $anon.

So you have built this

$anon = [1, 3, 5, 7, 9]

$aref = [ \ [1, 3, 5, 7, 9] ]

So

${$aref}[0]          is \ [1, 3, 5, 7, 9]
${${$aref}[0]}       is [1, 3, 5, 7, 9]
${${${$aref}[0]}}[2] is 5

But why are you working with references to arrays at all, and especially references to scalars? It would be best to begin with an ordinary array, and write

my @array = ( 1, 3, 5, 7, 9 );
my $aref = \@array;

print $aref->[2];

output

5

Upvotes: 4

Related Questions