【问题标题】:Comparing two hash values perl [duplicate]比较两个哈希值perl [重复]
【发布时间】:2014-06-18 22:44:22
【问题描述】:

休息后我正在研究 perl。如果我不清楚,请询问。

我有一个哈希值。

REST123=>{'test' => 'A',
          'test1'=> 'B',
          'test2'=> 'C'
          'test3'=> 'D'
         }
REST425=>{'test' => 'A',
          'test1'=> 'C',
          'test2'=> 'C'
          'test3'=> 'B'
         }

REST234=>{'test' => 'A',
          'test1'=> 'B',
          'test2'=> 'C'
          'test3'=> 'D'
         }

我想比较所有 REST* 中的 ABCD。结果应该是这样的。

REST123 REST425 4 1(mismatch) 
REST123 REST234 4 0 (mismatch)

我尝试将哈希复制到另一个上,但这不起作用。任何简单的访问它们进行比较的方法都会非常感激

谢谢

【问题讨论】:

标签: perl hash compare


【解决方案1】:

我不得不猜测一下,但我的水晶球告诉我你需要以下代码。

#!/usr/bin/perl
use warnings;
use strict;

my %hash
    = (
       REST123 => { test  => 'A',
                    test1 => 'B',
                    test2 => 'C',
                    test3 => 'D',
                  },
       REST425 => { test  => 'A',
                    test1 => 'C',
                    test2 => 'C',
                    test3 => 'B',
                  },
       REST234 => { test  => 'A',
                    test1 => 'B',
                    test2 => 'C',
                    test9 => 'D',
                  },
      );

for my $k1 (keys %hash) {
    for my $k2 (grep $k1 gt $_, keys %hash) {
        my %h;
        $h{$_} ++ for map keys %{ $hash{$_} }, $k1, $k2;
        my @same = grep $h{$_} == 2, keys %h;
        print join ' ', $k1, $k2, scalar @same,
            scalar grep $hash{$k1}{$_} ne $hash{$k2}{$_}, @same;
        print "\n";
    }
}

请注意,它返回 2 个不匹配项,而不是 1 个,如 'B' ne 'C' (test1) 和 'D' ne 'B' (test3)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-12
    • 2016-09-05
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多