【问题标题】:Pushing a hash to an existing hash in Perl将哈希推送到 Perl 中的现有哈希
【发布时间】:2012-09-23 19:23:48
【问题描述】:

我是 Perl 新手,所以你必须原谅我的代码。

我正在读取一个树形结构的文件(如 xml,实际上不是),我想通过树foreach,如果某个“节点”没有子节点,我想插入它.很简单。

这是我的代码:

foreach $key ( @{$struct->{'transferBatch'}->{'callEventDetails'} } ) {

    foreach ( keys %{$key} ) {

        if ( $_ eq "mobileTerminatedCall" ) {

            if ( defined $key->{$_}->{'basicServiceUsedList'} ) {

                if ( defined $key->{$_}->{'basicServiceUsedList'}[0]->{'chargeInformationList'} ) {

                    if ( not defined $key->{$_}->{'basicServiceUsedList'}[0]->{'chargeInformationList'}[0]->{'CallTypeGroup'} ) {

                        $CallTypeGroup = {                          
                                "CallTypeLevel1:" => "0",
                            "CallTypeLevel2:" => "0",
                            "CallTypeLevel3:" => "0"

                        };                          

                        #Doesn't work! 
                        $key->{$_}->{'basicServiceUsedList'}[0]->{'chargeInformationList'}[0]{'CallTypeGroup'} =  $CallTypeGroup;
                    }
                }
            }
        }
    }
}

迭代工作正常,但我的 push 调用失败,说它不是 ARRAY 引用。我觉得我很接近了,但我需要该行将 $CallTypeGroup 哈希作为一个孩子插入到当前位置。

感谢任何帮助!

【问题讨论】:

  • 使用引用将复杂的数据结构存储为标量。

标签: perl hash push


【解决方案1】:
$key->{$_}->{'basicServiceUsedList'}[0]->{'chargeInformationList'}[0]

包含对此处创建的哈希的引用(如果不是更早):

if ( not defined
   $key->{$_}{basicServiceUsedList}[0]
      ->{chargeInformationList}[0]
         ->{CallTypeGroup} )

您没有说明您想要什么数据结构,所以除了解释该消息外,我不确定我们能提供哪些帮助。我认为您只是想将 if 更改为

if ( not defined
   $key->{$_}{basicServiceUsedList}[0]
      ->{chargeInformationList}[0] )

顺便说一句,您确实应该使用变量来保存中间引用,而不是使用这么长的“名称”。

顺便说一句,我对所有那些硬编码的零索引高度怀疑。

【讨论】:

  • if 语句按预期工作,这意味着如果“CallTypeGroup”未定义为子项,我需要添加它。在我循环之前,零是占位符,到目前为止,我只想得到一个工作原型。
  • 我没说没有。我说我不知道​​你是否不告诉我们你想要什么数据结构。
  • $key->{$_}->{'basicServiceUsedList'}[0]->{'chargeInformationList'}[0]是hash,所以想加CallTypeGroup,小时候也是hash。
  • @OnResolve, push 添加到 数组push 中可能缺少 ->{CallTypeGroup}
  • 哇!好吧,这验证了我收到的错误消息:-P。因此,我更新了我的问题以反映添加到哈希中,但虽然我没有收到错误消息,但哈希似乎保持不变。
猜你喜欢
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 2017-01-04
  • 2020-07-19
  • 2013-12-20
  • 2013-08-10
相关资源
最近更新 更多