【发布时间】:2016-07-19 00:11:36
【问题描述】:
我正在阅读伦敦的“不耐烦的 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 = [];
谢谢你启发我。
【问题讨论】:
-
这里
[]有两种用法。$scal->[2]进行数组索引查找。[]创建对匿名数组的引用。
标签: arrays perl autovivification