我遇到了问题。我正在尝试为2个哈希值进行引用,然后在子例程中对它们进行比较。但是,有一个错误:
不能在compareHashes.pl第10行使用未定义的值作为HASH参考。
我的代码是:
use strict;
use warnings;
use feature qw(say);
my $hash_1; my $hash_2;
compareHashes($hash_1, $hash_2);
sub compareHashes{
say "the first hash:", "\n", %$hash_1;
say "the second hash:", "\n", %$hash_2;
if ((keys(%$hash_1) eq keys(%$hash_2)) and (values(%$hash_1) eq values(%$hash_2))){
say "Two above hashes are equal";}
else {
say "Two above hashes are not equal";
}
};
my %hash1 = (ITALY => "ROME",
FRANCE => "PARIS"
);
my %hash2 = ( ITALY => "MILAN",
FRANCE => "PARIS"
);
my %hash3 = (ITALY => "ROME" );
my %hash4 = (SPAIN => "ROME",
FRANCE => "PARIS"
);
my $hash1_r = \%hash1;
my $hash2_r = \%hash2;
my $hash3_r = \%hash3;
my $hash4_r = \%hash4;
compareHashes ($hash1_r, $hash1_r);
compareHashes ($hash1_r, $hash2_r);
compareHashes ($hash1_r, $hash3_r);
compareHashes ($hash1_r, $hash4_r);
请告诉我有什么问题。感谢您的帮助。
答案 0 :(得分:5)
您从未分配到$hash_1
和$hash_2
!
my ($hash_1, $hash_2) = @_;
你遇到的问题比较多,但是,标量上下文中的keys
和values
都会返回哈希中的元素数,因此您只需检查两个哈希值是否相同!
sub are_hashes_equal {
my ($hash1, $hash2) = @_;
{
my %set;
++$set{$_} for keys(%$hash1);
--$set{$_} for keys(%$hash2);
return 0 if grep { $_ } values(%set);
}
for my $key (keys(%$hash1)) {
return 0 if $hash1->{$key} ne $hash2->{$key};
}
return 1;
}