【问题标题】:Perl search for a value in hash of hash and reassign to another hashPerl 在散列的散列中搜索一个值并重新分配给另一个散列
【发布时间】:2014-07-27 18:31:27
【问题描述】:

我有一个示例哈希数据 %dsr_config 转储为

$VAR1 = 'dc';
$VAR2 = {
          'Alias' => 'DC',
          'Address' => 'street1, street2, '
        };
$VAR3 = 'dsr';
$VAR4 = {
          'daddr' => '192.168.1.1',
          'dscp' => '2',
          'Vip_enabled' => 'True',
          'BL' => '4,8',
          'subnet' => '255.255.255.255'
        };
$VAR7 = 'backup';
$VAR8 = {
          'backup' => 'enabled'
        };    

现在,我正在尝试查找哈希

$VAR3 = 'dsr';
$VAR4 = {
          'daddr' => '192.168.1.1',
          'dscp' => '2',
          'Vip_enabled' => 'True',
          'BL' => '4,8',
          'subnet' => '255.255.255.255'
        };

因为它的值 'Vip_enabled' => 'True',

我写的是

    foreach my $key1 (keys %dsr_config) {
            foreach my $key2 (keys $dsr_config{$key1}){
                    if ($key2 =~ /Vip_enabled/){
                            %dsr_config = $dsr_config{$key1};
                            }
                    }
            }

print Dumper %dsr_config;

我正在尝试仅使用所需数据覆盖现有的 %dsr_config。但我得到了

Reference found where even-sized list expected at ./test.pl line 43.
Type of argument to keys on reference must be unblessed hashref or arrayref at ./test.pl line 41.
Line 43 is   %dsr_config = $dsr_config{$key1};
Line 41 is   foreach my $key2 (keys $dsr_config{$key1}){

我在这里做错了什么?这个错误是什么意思?

【问题讨论】:

    标签: perl loops hash


    【解决方案1】:

    内部循环应该是:

    foreach my $key2 (keys %{$dsr_config{$key1}}){
        if ($key2 =~ /Vip_enabled/){
            %dsr_config = ($key1 => $dsr_config{$key1});
        }
    }
    

    $dsr_config{$key1} 是对哈希的引用,如果要循环键,则必须取消引用。

    另外,我猜你想在找到Vip_enabled 后退出外循环,因为下一次迭代将产生未定义的结果。

    OUTERLOOP:
    foreach my $key1 (keys %dsr_config) {
        foreach my $key2 (keys %{$dsr_config{$key1}}) {
            if ($key2 =~ /Vip_enabled/){
                %dsr_config = ($key1 => $dsr_config{$key1});
                last OUTERLOOP;
            }
        }
    }
    

    【讨论】:

    • 谢谢 M42。我试图理解,在内部循环中使用 $dsr_config{$key1} 和 %{$dsr_config{$key1}} 有什么区别?如果我执行打印 Dumper $dsr_config{$key1},它会打印密钥 dsr 的哈希内容。
    • 这项工作,如果我将值分配给一个新的哈希值,比如 %dsr_config_new。我无法让 %dsr_config 被新值覆盖。旧值仍然存在。我需要在 if 语句之前执行 delete 吗?
    【解决方案2】:

    大概是这样的:

    foreach my $key2 (keys $dsr_config{$key1}){
    

    应该是:

    foreach my $key2 (keys %{$dsr_config{$key1}}){
    

    键需要一个哈希。

    同样...

    %dsr_config = %{$dsr_config{$key1}};
    

    但仅凭一个片段很难确定。

    【讨论】:

    • 谢谢 John C。我试图理解,在内循环中使用 $dsr_config{$key1} 和 %{$dsr_config{$key1}} 有什么区别?如果我执行打印 Dumper $dsr_config{$key1},它会打印密钥 dsr 的哈希内容。
    • 要使用 dumper 你必须给它一个参考。所以如果你有一个哈希,你必须说 Dumper(\%hash)。 %{ 取消引用引用。引用是存储变量地址的变量。 (一个指针)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 2011-05-08
    • 2014-10-23
    • 1970-01-01
    • 2011-02-15
    • 2012-10-25
    • 2021-02-04
    相关资源
    最近更新 更多