【问题标题】:Check if key exists in hash using value from another hash as hash name使用来自另一个散列的值作为散列名称检查散列中是否存在键
【发布时间】:2014-11-11 05:00:36
【问题描述】:

我在回调中返回了一个变量 $breed,我正在检查我以前是否见过它,如果没有,则通过执行以下操作将其存储在 %hash 中:

    if (exists $hash{$breed}) {
    #exists
    } else {
    #add it
    $hash{$breed};
    }

现在,因为我想在单独的哈希中跟踪这些独特的 $breeds,所以我创建了另一个哈希来保留新的哈希名称

%hashnames =(cats => 'cathash',
            dogs => 'doghash');
my %cathash = ();
my %doghash = ();

由于我也从回调中返回了 $species,我知道我可以进行查找以获取我应该添加 $breed 的正确哈希:

$hashnames {$species}

我认为类似以下的内容可以,但事实并非如此:

if (exists ${$hashnames {$species}}{$breed}){
#exists
}else{
#add it
${$hashnames {$species}}{$breed};
}

实际上,有数百个物种和品种。这可能吗?也许我做错了?谢谢。

【问题讨论】:

    标签: perl hash hashmap exists


    【解决方案1】:

    你可以做一个hash of hashes:

    我不确定您是如何获取数据的,但这里有一个可能的示例:

    my @lol = (['cats', 'persian cat'], ['dogs', 'border collie'], ['cats', 'persian cat'], ['dogs', 'german shepherd']); #generating data
    my (%cats, %dogs);
    my %species = ('cats' => \%cats, 'dogs' => \%dogs);
    
    for my $specie_breed(@lol) {
      my ($s, $b) = @{$specie_breed};
      $species{$s}->{$b}++;
    }
    
    print Dumper \%species;
    

    结果:

    $VAR1 = {
              'cats' => {
                          'persian cat' => 2
                        },
              'dogs' => {
                          'german shepherd' => 1,
                          'border collie' => 1
                        }
            };
    

    这是一个在散列中使用带有跳过的数组的示例:

    my @lol = (['cats', 'persian cat'], ['dogs', 'border collie'],
               ['cats', 'persian cat'], ['dogs', 'german shepherd'],
               ['cats', 'Siamese']); #generating data
    my (@cats, @dogs);
    my %species = ('cats' => \@cats, 'dogs' => \@dogs);
    
    for my $specie_breed(@lol) {
      my ($s, $b) = @{$specie_breed};
      if(! grep(/$b/, @{$species{$s}})) {
        push @{$species{$s}}, $b;
     }
    }
    
    print Dumper \%species;
    

    结果:

    $VAR1 = {
              'dogs' => [
                          'border collie',
                          'german shepherd'
                        ],
              'cats' => [
                          'persian cat', #only adds it once
                          'Siamese'
                        ]
            };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多