Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 300
Gal Goldman Avatar asked Dec 13 '22 10:12

Gal Goldman


2 Answers

${@{$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
like image 119
cjm Avatar answered Jan 04 '23 00:01

cjm


This is how I would do it:

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

Output:

b
like image 29
Jared Ng Avatar answered Jan 03 '23 23:01

Jared Ng