0

我正在阅读伦敦的“不耐烦的 perl”。我正在测试“参考”一章中的一个示例。我想知道为什么在引用的自动激活中我需要在 [] 中放置一个数字(任何数字),而在声明一个数组时,我可以只使用 [] 作为空数组。谢谢。

#!/usr/bin/env perl
use warnings;
use strict;
use Data::Dumper;

my $scal;
my $val = $scal->[2]->{somekey}->[1]->{otherkey}->[7]; 
# fails if [] instead of [7] or [1] or [99999];
# same result if [7] or [1] or [99999] is used;

$val->[3] = 19;

print Dumper $scal;
print "========\n";
print Dumper $val;
print "========\n";
print Dumper []; # this does not fail; 

错误消息是“referenceTest.pl 第 7 行的语法错误,靠近“[]”全局符号“$val”需要在 referenceTest.pl 第 15 行显示明确的包名称。由于编译错误,referenceTest.pl 的执行中止。”

================== 当它使用[7]工作时,结果是:

$VAR1 = [
          undef,
          undef,
          {
            'somekey' => [
                           undef,
                           {
                             'otherkey' => []
                           }
                         ]
          }
        ];
========
$VAR1 = [
          undef,
          undef,
          undef,
          19
        ];
========
$VAR1 = [];

谢谢你启发我。

4

2 回答 2

3

->[]正在寻址一个数组条目。当然,你需要一个索引。自动生存只是寻址不存在的东西的副作用。如果你想赋值,那么,正如 Captain Obvious 很容易建议的那样,使用赋值运算符=my $val = ($scal->[2]->{somekey}->[1]->{otherkey} = []);

于 2016-07-19T01:01:23.973 回答
0

在这里http://perlmaven.com/autovivification很好地解释了自动生存

于 2016-08-02T03:58:21.370 回答