【问题标题】:Why am I getting "Can't use string ("FormFields") as a HASH ref while "strict refs" in use" error为什么我得到“不能使用字符串(“FormFields”)作为哈希引用而“使用严格引用”错误
【发布时间】:2016-10-04 22:27:34
【问题描述】:

我该如何解决这个错误? @names 包含 'foo','bar'

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};
};

在 ./xmltest.pl 第 263 行使用“严格引用”时,不能使用字符串(“FormFields”)作为 HASH 引用。

【问题讨论】:

    标签: perl data-structures


    【解决方案1】:

    您正在尝试将列表分配给哈希中的$foo$bar(在分配中使用括号...括号表示列表),您真正想要分配的是哈希引用。

    在 Perl 中,数据结构第一层下的任何内容都必须是引用。

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

    $foo$bar 分配中,将我指出的括号更改为大括号:$foo =&gt; {...}, $bar =&gt; {...},它表示匿名哈希(引用)。

    整个哈希分配应该是这样的:

    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
                           }
        };
    

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 1970-01-01
      • 2021-09-23
      • 2011-12-19
      • 1970-01-01
      • 2018-04-08
      • 2020-05-22
      • 2018-04-06
      • 1970-01-01
      相关资源
      最近更新 更多