2016-10-04 34 views
0

我該如何解決這個錯誤? @names包含「富」,「酒吧」爲什麼我在使用「嚴格參考」時無法使用字符串(「FormFields」)作爲HASH參考「錯誤

my %PDFData = (
foo => (
    FormFields => $FirstXML, 
    SignFields => $FirstXMLSign, 
), 
bar => (
    FormFields => $SecondXML, 
    SignFields => $SecondXMLign, 
), 
); 
my @names = @inputnames; 
my $formfields; 
my $signfields; 
for my $i (0 .. $#names) { 
$formfields .= $PDFData{ $names[$i] }{FormFields}; 
$signfields .= $PDFData{ $names[$i] }{SignFields}; 
}; 

不能使用字符串(「FormFields」)作爲HASH裁判而「嚴格裁判」在使用中./xmltest.pl線263

回答

2

你正試圖在散列內分配一個列表$foo$bar(在賦值中使用parens ... parens代表一個列表),其中你真正想要分配的是散列引用。

在Perl中,數據結構的第一級下的任何東西都必須是引用。

$bar => (# <-- that parens denotes a list 
    FormFields => $SecondXML, 
    SignFields => $SecondXMLign, 
) # <-- 

$foo$bar分配,更改我指出,以括號內的括號:$foo => {...}, $bar => {...},它代表一個匿名散列(參考)。

整個哈希分配應該是這樣的:

my %PDFData = (
    $foo => { 
     FormFields => $FirstXML, 
     SignFields => $FirstXMLSign, 
    }, 
    $bar => { 
     FormFields => $SecondXML, 
     SignFields => $SecondXMLign, 
    }, 
); 

如果你是散的,而不是散列內渴望數組,你會使用括號[],它表示一個匿名陣列(參考) :

my %hash = (
    $foo => [ 
     1, 
     2, 
    ], 
    $bar => [ 
     3, 
     4, 
    ], 
); 

另外,結識Data::Dumper幫助自己獲得了視覺的第一步調試/故障排除複雜的數據結構。下面是你有什麼(列表)與哈希引用賦值的例子:

use warnings; 
use strict; 

use Data::Dumper; 

my %h = (
    first_level => (
     second_level => 1, 
    ), 
); 

print Dumper \%h; 

%h = (
    first_level => { 
     second_level => 1, 
    }, 
); 

print Dumper \%h; 

...這是在輸出的區別:

# the list assignment output 

$VAR1 = { 
     '1' => undef, 
     'first_level' => 'second_level' 
    }; 

# the proper hash ref method output 

$VAR1 = { 
     'first_level' => { 
         'second_level' => 1 
         } 
    }; 
相關問題