0

我有以下哈希,我需要找到最上面的哈希值64. 我尝试了一些解决方案无济于事,并且对 Perl 语法不太熟悉以使其工作。

我拥有的哈希

$VAR1 = { 
    '6' => [ '1000', '2000', '4000' ],
    '4' => [ '1000', '2000', '3000' ]
}; 

我需要的哈希

$VAR1 = {
    '6' => ['4000'],
    '4' => ['3000'],
    'Both' => ['1000','2000']
}
4

2 回答 2

1
  1. 查找所有常见元素,例如通过哈希去重。
  2. 找出所有不常见的元素。

给定两个数组@x, @y,这意味着:

use List::MoreUtils 'uniq';

# find all common elements
my %common;
$common{$_}++ for uniq(@x), uniq(@y); # count all elements
$common{$_} == 2 or delete $common{$_} for keys %common;

# remove entries from @x, @y that are common:
@x = grep { not $common{$_} } @x;
@y = grep { not $common{$_} } @y;

# Put the common strings in an array:
my @common = keys %common;

现在剩下的就是做一些取消引用等,但这应该是相当微不足道的。

于 2013-07-29T19:21:56.157 回答
0

不需要其他模块。perl 哈希对于查找 uniq 或公共值非常有用

my %both;
# count the number of times any element was seen in 4 and 6
$both{$_}++ for (@{$VAR1->{4}}, @{$VAR1->{6}});
for (keys %both) {
  # if the count is one the element isn't in both 4 and 6
  delete $both{$_} if( $both{$_} == 1 );
}
$VAR1->{Both} = [keys %both];
于 2013-07-30T02:47:18.357 回答