Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

perl - how to pass hash reference to a subroutine

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...