【发布时间】:2012-03-29 08:19:11
【问题描述】:
我必须匹配两个哈希表,但它的键不匹配。所以我到达每个哈希表并按值匹配。所以下面的代码不起作用:
sub _findHashElt
{
my ($this, $hashTarget) = @_;
my $isFound = 0;
my $isItemFound = 1;
my $isHashFound = 0;
my $result = undef;
my %hashTable=%{$this->{templates}};
my %hashTargetHash=%{$hashTarget};
my %hashSubTable = undef;
while ( (my ($key, $value) = each(%hashTable))
and ($isFound == 0 ))
{
$isItemFound = 1;
$isHashFound = 0;
####################################
# DOES NOT WORK
%hashSubTable = %{$hashTable{$key}};
####################################
while ( (my ($subKey, $subValue) = each(%hashTargetHash))
and ($isItemFound == 1 ))
{
$isItemFound = 0;
while ( (my ($subTableKey, $subtableValue) = each(%hashSubTable))
and ($isItemFound == 0 ))
{
$isHashFound = 1;
$isItemFound = ($subValue eq $subtableValue) ? 1 : 0;
}
}
if ($isItemFound == 1 && $isHashFound == 1) {
$isFound = 1;
$result = $key;
}
}
return $result;
}
以下代码有效:
sub _findHashElt
{
my ($this, $hashTarget) = @_;
my $isFound = 0;
my $isItemFound = 1;
my $isHashFound = 0;
my $result = undef;
my %hashTable=%{$this->{templates}};
my %hashTargetHash=%{$hashTarget};
my %hashSubTable = undef;
while ( (my ($key, $value) = each(%hashTable))
and ($isFound == 0 ))
{
$isItemFound = 1;
$isHashFound = 0;
while ( (my ($subKey, $subValue) = each(%hashTargetHash))
and ($isItemFound == 1 ))
{
####################################
# WORK
%hashSubTable = %{$hashTable{$key}};
####################################
$isItemFound = 0;
while ( (my ($subTableKey, $subtableValue) = each(%hashSubTable))
and ($isItemFound == 0 ))
{
$isHashFound = 1;
$isItemFound = ($subValue eq $subtableValue) ? 1 : 0;
}
}
if ($isItemFound == 1 && $isHashFound == 1) {
$isFound = 1;
$result = $key;
}
}
return $result;
}
请谁能告诉我,请问是什么问题?
编辑
#############################################
################# TEST PART #################
#############################################
my $this = {"templates" => {}};
my $example = {'key0' => {'key00' => 'test00', 'key01' => 'test01', 'key02' => '0', 'key03' => 'test03'},
'key1' => {'key00' => 'test10', 'key01' => 'test11', 'key02' => '1', 'key03' => 'test13'},
'key2' => {'key00' => 'test20', 'key01' => 'test21', 'key02' => '1', 'key03' => 'test23'},
'key3' => {'key00' => 'test30', 'key01' => 'test31', 'key02' => '0', 'key03' => 'test33'}};
my $expected = {'key00' => 'test00', 'key01' => 'test01', 'key02' => '0', 'key03' => 'test03'};
$this->{templates}=$example;
_findHashElt($this, \%expected );
在第一种情况下,没有找到密钥,而在第二种情况下,已经找到了密钥......
编辑
第一种情况:
$ perl myTest.pl
Key not found
第二种情况:
$ perl myTest.pl
Key found
{
key01 : test01
key00 : test00
key03 : test03
key02 : 0
}
编辑
还有一点,我觉得会有用的
$ perl --version
This is perl, v5.10.1 (*) built for i686-cygwin-thread-multi-64int
(with 13 registered patches, see perl -V for more detail)
【问题讨论】:
-
通常最好将您的问题归结为最小版本。
-
我不知道如何将我的问题归结为最小版本。但我可以添加一个完整的示例,它可以提供帮助。
-
does not work是什么意思?您能否提供一些输入和预期输出的示例数据? -
不工作意味着没有找到密钥。如果我转储哈希表,相同的代码可以工作,它可以找到正确的键...
-
@binogure 如果您的代码版本可以运行,为什么需要帮助?