如果密钥存在于hash1而不是hash2中,则“执行某些操作”

时间:2013-09-02 13:15:31

标签: perl hash undefined declaration

我写了一些代码,在3个不同的HoA中找到重叠的密钥,其中包含一些我稍后会对它们进行排序的信息:

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

my @intersect;
for my $key (sort keys %hash1) {
    if (exists $hash2{$key} && $hash3{$key} ) {
        my ($hit1, $percent_id1) = @{ $hash1{$key}[-1] };
        my ($hit2, $percent_id2) = @{ $hash2{$key}[-1] };
        my ($hit3, $percent_id3) = @{ $hash3{$key}[-1] };
        push @intersect, "$key\tC1:[$condition1]$hit1 [$percent_id1]\tC2:[$condition2]$hit2 [$percent_id2]\tC3:[$condition3]$hit3 [$percent_id3]\n\n";\n";
    }
}

我正在尝试调整脚本以查找存在于以下内容中的密钥:

  • hash1和hash2,但不是hash3
  • hash2和hash3,但不是hash1
  • hash1和hash3,但不是hash2

我正在使用它(例如第一次):

elsif (exists $hash2{$key} && !exists $hash3{$key} ) { # Is this the right way to specify a 'not exists'?
    my ($hit1, $percent_id1) = @{ $blast1{$key}[-1] };
    my ($hit2, $percent_id2) = @{ $blast2{$key}[-1] };
    push @intersect, "$key\tC1:[$condition1]$hit1 [$percent_id1]\tC2:[$condition2]$hit2 [$percent_id2]\n";
}

稍后在代码中我遍历每个@intersect以便对它们进行排名(以下内容的详细信息在很大程度上无关紧要):

foreach (@intersect) {
    chomp;
    my (@condition1_match) = ($_ =~ /C1:.*?Change:(-?\d+\.\d+|-?inf)/);
    @q_value1 = ($_ =~ /C1:.*?q:(\d+\.\d+)/);
    my (@percent_id) = ($_ =~ /C\d+:.*\[(\d+\.\d+)\]/);
    push @percentages, "@percent_id%";
    my (@condition2_match) = ($_ =~ /C2:.*?Change:(-?\d+\.\d+|-?inf)/);
    @q_value2 = ($_ =~ /C2:.*?q:(\d+\.\d+)/);
    my (@condition3_match) = ($_ =~ /C3:.*?Change:(-?\d+\.\d+|-?inf)/);
    @q_value3 = ($_ =~ /C3:.*?q:(\d+\.\d+)/);

    my $condition1_match = $condition1_match[0] // $condition1_match[1];
    my $condition2_match = $condition2_match[0] // $condition2_match[1];
    my $condition3_match = $condition3_match[0] // $condition3_match[1];

    if (abs $condition1_match > abs $condition2_match && abs $condition1_match > abs $condition3_match) {
            push @largest_change, $condition1_match;
        } 
        elsif (abs $condition2_match > abs $condition1_match && abs $condition2_match > abs $condition3_match) {
            push @largest_change, $condition2_match;
        }       
        else { push @largest_change, $condition3_match}

显然,如果一个键存在于两个而不是三个哈希中,那么将会有很多变量为undef的实例,因此我得到了很多Use of uninitialized value in...

我应该为每个变量添加if (defined ($variable ))前缀吗?

1 个答案:

答案 0 :(得分:3)

my %seen;
++$seen{$_} for keys(%hash1), keys(%hash2), keys(%hash3);
for (keys(%seen)) {
   next if $seen{$_} != 2;
   print("$_ is found in exactly two hashes\n");
}

此版本跟踪密钥的来源:

my %seen;
push @{ $seen{$_} }, 'hash1' for keys(%hash1);
push @{ $seen{$_} }, 'hash2' for keys(%hash2);
push @{ $seen{$_} }, 'hash3' for keys(%hash3);
for (keys(%seen)) {
   next if @{ $seen{$_} } != 2;
   print("$_ found in @{ $seen{$_} }\n");
}