【问题标题】:Why perl hash does not take certain string variables as its key?为什么 perl hash 不将某些字符串变量作为其键?
【发布时间】:2018-03-06 23:17:15
【问题描述】:

当我尝试为多级散列赋值时

        use strict;
        # multi step before following code

        $res{cccc}{1}{sense} = '+'; # no problem
        my $ttsid = 'NZAEMG01000001';
        $res{$ttsid}{1}{sense} = '+'; # no problem
        $ttsid = 'NZAEMG01000001.1';
        $res{$ttsid}{1}{sense} = '+'; # no problem
        print "before sid is $sid\n"; # print out NZ_AEMG01000001t1

到这一步,程序运行良好

        $res{$sid}{1}{sense} = '+'; # even this gets problem too

但是,当我将此行添加到程序中时,我得到了错误

 Can't use string ("57/128") as a HASH ref while "strict refs" in use

使用以下方法进行更多测试

        $sid = 'placement'; # result
        $res{$sid}{1}{sense} = '+';

这没有问题。所以在我看来,这条线

        $sid = 'placement'; # result

将 $sid 值从 NZ_AEMG01000001t1 更改为放置,这使得该行

        $res{$sid}{1}{sense} = '+';

有效。这种翻译成

        $res{'NZ_AEMG01000001t1'}{1}{sense} = '+'; # Not working
        $res{'placement'}{1}{sense} = '+'; # working

确实,当我像这样将 $ttsid 更改为 $sid 值时

        $ttsid = 'NZ_AEMG01000001t1'; # which is $sid value
        $res{$ttsid}{1}{sense} = '+'; # has problem

这也有问题。

为什么?

【问题讨论】:

  • 您的示例甚至无法编译。 %res 未声明。
  • 是的,# multi step before following code 部分是实际问题所在。你应该先创建一个minimal reproducible example

标签: perl hash key assign


【解决方案1】:

因为在某些时候你做了相当于

$res{'NZ_AEMG01000001t1'} = %some_other_hash;

$res{'NZ_AEMG01000001t1'} 设置为字符串,而不是对(嵌套)散列的引用。

该错误表明您正在尝试使用一个字符串,就好像它是一个 hashref。您的数据结构不包含您认为的内容。

【讨论】:

  • 你是对的。我在每一步都倾倒,找到了你说的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 2021-10-31
  • 2020-11-01
  • 1970-01-01
相关资源
最近更新 更多