简体   繁体   English

Perl - 数组引用,使用严格

[英]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:此代码在 Perl v5.8.6 中顺利通过,现在我安装了 v5.10.1,出现运行时错误:

Can't use string ("4") as an ARRAY ref while "strict refs" in use at...不能使用字符串(“4”)作为数组引用,而“严格引用”在...中使用

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谢谢,盖尔

${@{$region}}[3] was never the correct way to access an arrayref. ${@{$region}}[3]从来都不是访问数组引用的正确方法。 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).我不太确定它是什么意思,我认为 Perl 也不是(因此不同版本的 Perl 中的行为不同)。

The correct ways are explained in perlref : 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

This is how I would do it:我会这样做:

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

Output: Output:

b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM