0

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];
4
  • 2
    Maybe: @{ $list[0] }? Commented Mar 25, 2020 at 0:30
  • @GMB, Thanks, that works! Do you happen to know why sticking an "@" before $list[0] doesn't work like @$r1 does? Commented Mar 25, 2020 at 0:33
  • Precedence issue. (You can also use postderef syntax - $list[0]->@*) Commented Mar 25, 2020 at 0:41
  • See perldoc.perl.org/perlref.html#Using-References where this is mentioned. Commented Mar 25, 2020 at 0:45

1 Answer 1

5

@$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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.