2016-07-19 29 views
0

我正在閱讀倫敦的「impatient perl」。我正在測試「參考」一章中的一個例子。我很奇怪,爲什麼在自動激活參考我需要把一些(任何數字)[]內,而在聲明數組,我可以只使用[]作爲空數組。謝謝。perl autovivification數組

#!/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的referenceTest.pl線15.Execution中止明確包名由於彙編錯誤。「

================== 而當它工作使用[7],結果是:

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

感謝您啓發了我。

+0

有'的[]'這裏有兩個用途。 '$ scal - > [2]'進行數組索引查找。 '[]'創建對匿名數組的引用。 – aschepler

回答

3

->[]正在處理數組條目。當然你需要一個索引。 Autovivification只是解決某些不存在的問題的副作用。如果你想,而不是分配,那麼,作爲隊長明顯會很容易地想到,使用賦值運算符=my $val = ($scal->[2]->{somekey}->[1]->{otherkey} = []);

+0

非常感謝! – lisprogtor