ToniAz
ToniAz

Reputation: 440

Perl: Systematically dereferencing elements of anonymous array

The following gives me a compilation error Global symbol "$list" requires explicit package name at ./scratch line 19.. How can I correctly access an element in an anonymous array?

use warnings;
use strict;
use feature "say";

my @list1 = (10, 20, 30);
my @list2 = ("hello", "yellow", "mellow");
my $r1 = \@list1;
my $r2 = \@list2;

my @list = ($r1, $r2);

# Prints just fine
say join ", ", @$r1;
say join ", ", @$r2;

# This part gives compilation error
say join ", ", @$list[0];
say join ", ", @$list[1];

Upvotes: 0

Views: 92

Answers (1)

ikegami
ikegami

Reputation: 385915

@$list[0] is short for @{ $list }[0] but you want @{ $list[0] } (or $list[0]->@*).


@array[1,2,3]

is an array slice equivalent to

( $array[1], $array[2], $array[3] )

The syntax for an array slice is

@NAME[LIST]     # Named array
@BLOCK[LIST]    # A block returning a reference.
EXPR->@[LIST]   # An expression returning a reference.   Perl 5.24+

For example,

@array[1,2,3]
@{ $ref }[1,2,3]
$ref->@[1,2,3]

When the block contains only a simple scalar ($NAME or $BLOCK), the curlies of the block can be omitted.

For example,

@{ $ref }[1,2,3]

can be written as

@$ref[1,2,3]

This is what you had, but not you wanted. You wanted the elements of an array.

@NAME      # Named array
@BLOCK     # A block returning a reference.
EXPR->@*   # An expression returning a reference.   Perl 5.24+

For example,

@array
@{ $ref }
$ref->@*

Or in your case,

@{ $list[0] }
$list[0]->@*

As with an array slice, the curlies of the block can be omitted when the block contains only a simple scalar. But that's not what you have.


See Perl Dereferencing Syntax.

Upvotes: 5

Related Questions