【问题标题】:Accessing multi-level hash using scalar filled with keys使用填充键的标量访问多级哈希
【发布时间】:2023-03-03 13:55:02
【问题描述】:

我正在尝试做这样的事情:

my $xml_hash_ref = XML::Parser......


my %fields_to_check = (
            '{Key1}{Key2}{Key3}{Key4}' => '..another hash...'
            '{Key1}{DifferentKey2}'    => '...another hash...'
            '{Key1}{DifferentKey2}{DifferentKey3}'    =>  '...another hash...'
);

foreach my $key (keys %fields_to_check){
     my $value = $xml_hash_ref->$key;
}

本质上,我在解析 XML 时会得到这么大的哈希值。我想使用此配置散列 %fields_to_check 访问此散列结构中的这些不同值。Essential $key 是一串键,用于指示我想去的地方。有人知道这是否可能或知道其他解决方案吗?

【问题讨论】:

    标签: perl hash perl-data-structures


    【解决方案1】:

    这是一个粗略的想法:

    use strict;
    use warnings;
    
    my $deep_hash = {
        aa => {
            bb => { cc => 111, dd => 222 },
            ee => 333,
        },
        ff => 444,
    };
    
    sub dive {
        my $h = shift;
        for my $k (@_){
            return unless (ref($h) eq 'HASH' and exists $h->{$k});
            $h = $h->{$k};
        }
        return $h;
    }
    
    dive($deep_hash, qw(aa bb dd));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 2014-04-16
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      相关资源
      最近更新 更多