【问题标题】:In Perl, how should I populate this multilevel hash?在 Perl 中,我应该如何填充这个多级哈希?
【发布时间】:2018-01-17 18:13:51
【问题描述】:

我正在尝试找到 Perl 填充多级哈希的最佳方法,同时考虑到缺少的键。
所以我用这个:

if( !exists $customer_data{$customer_id} ) {  
     $customer_data{$customer_id} = {};    
}    
$customer_data{$customer_id}->{$salesman_name} //={};
$customer_data{$customer_id}->{$salesman_name}->{$timestamp} = 1;   

这很奇怪,因为我正在使用 exists//= 东西,但我不确定如何正确简洁地编写此代码。
结果类似于:

'1000' => {                                                                                             
    'jsmith' => {                                                                              
         1502121730 => 1,                                                           
         1512321730 => 1                                                        
     }                                                                              
} 

【问题讨论】:

    标签: perl hashtable


    【解决方案1】:

    perldoc perlreftut 中查看autovivification

    $customer_data{$customer_id}{$salesperson_name}{$timestamp} = 1;
    

    足够了。

    此外,您可能不希望有性别的变量名称。

    【讨论】:

    • 实际上我试图避免autovification,但我可能对此感到困惑。什么时候这么糟糕?
    • @Jim 当您查找(或使用)不存在的嵌套键/值时,这(可能和可能)不好。就像if ($rh{no_key}{other})——因为它随后创建了整个结构(以便能够查找正在检查的最后一部分),这可能是人们不想要的。但在这种情况下,您 分配 到该键,所以您 正在 手动执行自动激活所做的工作,正如 Sinan 的帖子所说。
    • @Jim 要抑制这一点,请参阅autovivification 模块(pragma)。但请仔细阅读。
    猜你喜欢
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2016-07-22
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2012-08-14
    相关资源
    最近更新 更多