我有像这样的多维哈希
%hash = {'5' => {'DS' => 'TESTD1',
'DN' => 'TESTD1',
'PP' => 'APPLE44'},
'6'=> {'DS' => 'TESTD2',
'DN' => 'TESTD2',
'PP' => 'APPLE44'},
'7'=>{'DS' => 'TESTD1',
'DN' => 'TESTD3',
'PP' => 'APPLE44'}
'8'=>{'DS' => 'TESTD1',
'DN' => 'TESTD1',
'PP' => 'ORANGE33' }
};
现在我想检查整个哈希的'PP'值和'DS'值之间是否存在唯一映射。 例如,第7个键不是唯一的,因为它与DS和PP值的第5个键相同。 只有当PP和DS值相同时,我才应该增加计数。
到目前为止,我已尝试使用'exists',但似乎没有按照我想要的方式工作,那么我们如何实现这一目标呢?
答案 0 :(得分:3)
您可能使用exists
遇到问题,因为您错误地定义了哈希。当您应使用%hash = { ... }
创建哈希或使用%hash = ( ... )
创建哈希引用时,可以$hash = { ... }
。阅读所有血腥细节的perldoc perlreftut。
使用另一个哈希来存储各种DS / PP组合,并使用它来检查唯一性。
use warnings;
use strict;
my $hash = {
'5' => {'DS' => 'TESTD1',
'DN' => 'TESTD1',
'PP' => 'APPLE44'},
'6' => {'DS' => 'TESTD2',
'DN' => 'TESTD2',
'PP' => 'APPLE44'},
'7' => {'DS' => 'TESTD1',
'DN' => 'TESTD3',
'PP' => 'APPLE44'},
'8' => {'DS' => 'TESTD1',
'DN' => 'TESTD1',
'PP' => 'ORANGE33'},
};
my %check_for_dups;
for my $key ( sort keys %$hash ) {
my $subhash = $hash->{ $key };
my $combo = join '_', 'DS', $subhash->{ DS }, 'PP', $subhash->{ PP };
$check_for_dups{ $combo }->{ $key } = 1;
}
my $found_dups = 0;
for my $combo ( sort keys %check_for_dups ) {
my @keys_for_combo = sort { $a <=> $b } keys %{ $check_for_dups{ $combo } };
if ( scalar @keys_for_combo > 1 ) {
print "Duplicate keys for combo '$combo' : " . join(',',@keys_for_combo) . "\n";
$found_dups = 1;
}
}
print "All combos are unique!\n"
unless $found_dups;
<强>输出强>
Duplicate keys for combo 'DS_TESTD1_PP_APPLE44' : 5,7
答案 1 :(得分:0)
这有效
my %dup;
if(exists($dup{'DS'}{'PP'}))
{
count++;
}
答案 2 :(得分:-1)
我使用的几乎与xxfelixxx答案相同,但在他的代码中我们找不到所有重复项,因为脚本存在(实际上已经死了:))当它找到第一个重复时。
因此我使用了数组的哈希来存储重复的索引,因此你知道重复的索引和它们的数量(数组值的数量)
#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';
my $hash = {'5' => {'DS' => 'TESTD1',
'DN' => 'TESTD1',
'PP' => 'APPLE44'},
'6'=> {'DS' => 'TESTD2',
'DN' => 'TESTD2',
'PP' => 'APPLE44'},
'7'=>{'DS' => 'TESTD1',
'DN' => 'TESTD3',
'PP' => 'APPLE44'},
'8'=>{'DS' => 'TESTD1',
'DN' => 'TESTD1',
'PP' => 'ORANGE33' }
};
my %result;
foreach (keys %{$hash}) {
my $n_key = $hash->{$_}{'DS'} . '_' . $hash->{$_}{'PP'};
if( ! defined $result{$n_key} ) {
$result{$n_key} = [ $_ ];
} else {
push @{$result{$n_key}}, $_;
}
}
foreach (keys %result) {
if( @{$result{$_}} > 1 ) {
my($DD, $PP) = split('_', $_);
print "Duplicated values found for DD => $DD, PP => $PP, ";
print "No of duplicates : ".scalar(@{$result{$_}})." and there respective indexes are @{$result{$_}}\n";
}
}
print "$_ : @{$result{$_}}\n" foreach(keys %result);
<强>输出强>
Duplicated values found for DD => TESTD1, PP => APPLE44, No of duplicates : 2 and there respective indexes are 7 5
TESTD2_APPLE44 : 6
TESTD1_ORANGE33 : 8
TESTD1_APPLE44 : 7 5