Search code examples
arraysperlreferencestrict

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


Solution

  • ${@{$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