How do I compare two hashes in Perl without using Data::Compare?

后端 未结 7 1450
春和景丽
春和景丽 2020-12-10 03:08

How do I compare two hashes in Perl without using Data::Compare?

7条回答
  •  悲哀的现实
    2020-12-10 03:45

    For comparing:

    sub HashCompare {
      my ( $a, $b ) = @_;
      my %rhash_1 = %$a;
      my %rhash_2 = %$b;
    
      my $key         = undef;
      my $hash_2_line = undef;
      my $hash_1_line = undef;
    
      foreach $key ( keys(%rhash_2) ) {
       if ( exists( $rhash_1{$key} ) ) {
        if ( $rhash_1{$key} ne $rhash_2{$key} ) {
         print "key $key in $file_1 = $rhash_1{$key} & $rhash_2{$key} in $file_2\n";
             }
           }
         }
         else {
            print "key $key in  $file_1 is not present in $file_2\n";
    
                #next;
            }
        }
    
        foreach my $comp_key ( keys %rhash_1 ) {
            if ( !exists( $rhash_2{$comp_key} ) ) {
                print MYFILE "key $comp_key in  $file_2 is not present in $file_1\n";
            }
        }
        return;
    }
    

    Creating hash with no duplicate keys:

    sub CreateHash {
        my (@key_val_file ) = @_;
        my $key_count      = 1;
        my %hash_key_val   = ();
        my $str4           = undef;
    
        local $/ = undef;
    
        foreach my $each_line (@key_val_file) {
                @key_val = split( /,/, $each_line );
                if ( exists( $hash_key_val{$key_val[0]} ) ) {
                        $key_count = $key_count + 1;
                        $str4      = $key_val[0] . " occurence-" . $key_count;
                        $hash_key_val{$str4} = $key_val[1];
                    }
                    else {
                        $hash_key_val{$key_name} = $key_val[1];
                    }
                }
            }
    
            $key_count = 1;
    
        close FILE;
    
        return %hash_key_val;
    }
    

提交回复
热议问题