【问题标题】:Perl defining undefined keysPerl 定义未定义的键
【发布时间】:2013-08-07 20:10:51
【问题描述】:

以下代码打印Key defined 3。 为什么 Perl 定义键 ABC ?我原以为这三个检查都是假的。我做错了什么?

#!/usr/bin/perl 
use warnings;
use strict;

my %Hash;

if(defined $Hash{'ABC'})
{
    printf("Key defined 1\n");
}

if(defined $Hash{'ABC'}{'Status'})
{
    printf("Key defined 2\n");
}

if(defined $Hash{'ABC'})
{
    printf("Key defined 3\n");
}

【问题讨论】:

    标签: perl hash key undefined autovivification


    【解决方案1】:

    $Hash{'ABC'}{'Status'} 自动激活 ABC 键(请参阅 perldoc perlrefwikipedia):

    use warnings;
    use strict;
    use Data::Dumper;
    
    my %Hash;
    
    if(defined $Hash{'ABC'})
    {
        printf("Key defined 1\n");
    }
    print Dumper(\%Hash);
    
    if(defined $Hash{'ABC'}{'Status'})
    {
        printf("Key defined 2\n");
    }
    print Dumper(\%Hash);
    
    if(defined $Hash{'ABC'})
    {
        printf("Key defined 3\n");
    }
    print Dumper(\%Hash);
    
    __END__
    
    $VAR1 = {};
    $VAR1 = {
              'ABC' => {}
            };
    Key defined 3
    $VAR1 = {
              'ABC' => {}
            };
    

    另请参阅 Data::Diverautovivification pragma,它们会阻止自动存活。

    【讨论】:

      【解决方案2】:
      $Hash{'ABC'}{'Status'}
      

      的缩写
      $Hash{'ABC'}->{'Status'}
      

      你所拥有的是一个取消引用。当取消引用的变量未定义时,自动激活会启动以创建适当类型的变量。这使得上述等价于

      ( $Hash{'ABC'} //= {} )->{'Status'}
      

      您可以通过避免取消引用未定义的内容来避免自动激活

      if ($Hash{'ABC'} && defined $Hash{'ABC'}{'Status'})
      

      或者你可以使用no autovivification;

      no autovivification;
      if (defined $Hash{'ABC'}{'Status'})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-13
        • 2014-09-17
        • 1970-01-01
        • 1970-01-01
        • 2018-05-20
        • 2022-01-21
        • 2011-10-08
        相关资源
        最近更新 更多