Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm stuck on a problem. I'm trying to make references for 2 hashes, then compare them in a subroutine. However, there is an error:

Can't use an undefined value as a HASH reference at compareHashes.pl line 10.

My code is:

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:", "
", %$hash_1;
    say "the second hash:", "
", %$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);

Please tell me what is wrong. I appreciate your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
364 views
Welcome To Ask or Share your Answers For Others

1 Answer

You never assigned to $hash_1 and $hash_2!

my ($hash_1, $hash_2) = @_;

You have more problems than that, however, both keys and values in scalar context return the number of elements in a hash, so you are simply checking if both hashes are of the same size!

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...