Gal Goldman
Gal Goldman

Reputation: 8869

Perl - Array reference, using strict

I have the following code:

my @array = ('a', 'b', 'c');

my $region = \@array;  # Returns an array reference
my $Value = ${@{$region}}[3];   

I am using strict;

This code passed smoothly in Perl v5.8.6, and now that I installed v5.10.1, I get a runtime error:

Can't use string ("4") as an ARRAY ref while "strict refs" in use at ...

I changed the code to the following, and that solved the issue:

my @array = ('a', 'b', 'c');

my $region = \@Array;
my @List = @{$region};
my $Value = $List[3];   

my question is, what's wrong with the previous way? What has changed between these two versions? What am I missing here?

Thanks, Gal

Upvotes: 4

Views: 2636

Answers (2)

cjm
cjm

Reputation: 62109

${@{$region}}[3] was never the correct way to access an arrayref. I'm not quite sure what it does mean, and I don't think Perl is either (hence the different behavior in different versions of Perl).

The correct ways are explained in perlref:

my $Value = ${$region}[3]; # This works with any expression returning an arrayref
my $Value = $$region[3];   # Since $region is a simple scalar variable,
                           # the braces are optional
my $Value = $region->[3];  # This is the way I would do it

Upvotes: 11

Jared Ng
Jared Ng

Reputation: 5071

This is how I would do it:

my @array = ('a', 'b', 'c');
my $region = \@array;
my $Value = $$region[1];
print $Value;

Output:

b

Upvotes: 2

Related Questions