删除键/值哈希对会留下键。为什么?

时间:2012-03-02 19:45:22

标签: perl hash

请考虑以下代码:

$foo{'bar'}->{'lala'} = "lol";
delete($foo{'bar'}->{'lala'});

当我运行此代码时,我希望“lala”条目完全消失(键和值)。但是,当我使用Dumper转储此哈希时,它看起来像这样:

$foo => {
    'bar' => {
        'lala' => {}
    }
}

为什么钥匙留在后面?我想删除值和键。以下是实际相关代码和结果。

用于删除的代码:

delete( $state->{calls}->{$call_id} );

输出BEFORE:

$VAR1 = bless( {
  'packet' => {},
  'calls' => {
    ' 1330718109168
' => {
      'eventcount' => 0,
      'caller_id_name' => ' 
',
  '    channels' => [
        ' 1330718109168
'
      ],
      'entered_time' => 1330718109,
      'caller_id_num' => ' 
'
    },
    ' 1330718097167
' => {
      'eventcount' => 277,
      'caller_id_name' => ' Cell Phone   NY
',
      'channels' => [
        ' 1330718097167
'
      ],
      'queue' => ' TEST_HUD_AMIEV
',
      'entered_time' => 1330718097,
      'caller_id_num' => ' 5555555
'
    }
}, 'main' );

输出后:

$VAR1 = bless( {
  'packet' => {},
  'calls' => {
    ' 1330718097167
' => {},
    ' 1330718109168
' => {}
}, 'main' );

2 个答案:

答案 0 :(得分:6)

我无法重现这个问题(Perl 5.14.2):

use strict;
use warnings;
use Data::Dumper;

my %foo;
$foo{bar}->{lala} = 'lol';
delete( $foo{bar}->{lala});
print Dumper \%foo;

输出

$VAR1 = {
          'bar' => {}
        };

答案 1 :(得分:0)

更新了更新问题的答案:

我清理了你的示例输入(使用行尾转义,因此可以将其复制/粘贴到调试器中):

$VAR1 = bless( \
{ \
  'packet' => {}, \
  'calls' => { \
    '1330718109168' => { \
      'eventcount' => 0, \
      'caller_id_name' => '', \
      'channels' => [' 1330718109168'], \
      'entered_time' => 1330718109, \
      'caller_id_num' => '' \
      }, \
    '1330718097167' => { \
      'eventcount' => 277, \
      'caller_id_name' => 'Cell Phone   NY', \
      'channels' => ['1330718097167'], \
      'queue' => 'TEST_HUD_AMIEV', \
      'entered_time' => 1330718097, \
      'caller_id_num' => '5555555' \
      } \
    } \
}, 'main' )

这是我在调试器中得到的内容:

  DB<85> x $VAR1
0  main=HASH(0x108d0a58)
   'calls' => HASH(0x108d09f8)
      1330718097167 => HASH(0x108d0938)
         'caller_id_name' => 'Cell Phone   NY'
         'caller_id_num' => 5555555
         'channels' => ARRAY(0x108d08f0)
            0  1330718097167
         'entered_time' => 1330718097
         'eventcount' => 277
         'queue' => 'TEST_HUD_AMIEV'
      1330718109168 => HASH(0x108d0848)
         'caller_id_name' => ''
         'caller_id_num' => ''
         'channels' => ARRAY(0x108d07b8)
            0  ' 1330718109168'
         'entered_time' => 1330718109
         'eventcount' => 0
   'packet' => HASH(0x108c4408)
        empty hash
  DB<86> delete $VAR1->{calls}->{'1330718097167'}

  DB<87> delete $VAR1->{calls}->{'1330718109168'}

  DB<88> x $VAR1
0  main=HASH(0x108d0a58)
   'calls' => HASH(0x108d09f8)
        empty hash
   'packet' => HASH(0x108c4408)
        empty hash

看起来它适合我(Cygwin的Perl 5.10.1)