1

我在这里有一段工作代码,我将六个哈希的键一起比较,以找到它们之间共有的键。然后,我将每个散列中的值组合成一个新散列中的值。我想做的是使它可扩展。我希望能够轻松地将 3 个哈希值与 100 个哈希值进行比较,而无需返回我的代码并对其进行更改。关于我将如何实现这一目标的任何想法?其余代码已经适用于不同的输入量,但这是让我卡住的部分。

my $comparison = List::Compare->new([keys %{$posHashes[0]}], [keys %{$posHashes[1]}], [keys %{$posHashes[2]}], [keys %{$posHashes[3]}], [keys %{$posHashes[4]}], [keys %{$posHashes[5]}]);
my %comboHash;
for ($comparison->get_intersection) {
$comboHash{$_} = ($posHashes[0]{$_} . $posHashes[1]{$_} . $posHashes[2]{$_} . $posHashes[3]{$_} . $posHashes[4]{$_} . $posHashes[5]{$_});
}
4

4 回答 4

1
my %all;
for my $posHash (@posHashes) {
   for my $key (keys(%$posHash)) {
      push @{ $all{$key} }, $posHash->{$key};
   }
}

my %comboHash;
for my $key (keys(%all)) {
   next if @{ $all{$key} } != @posHashes;
   $comboHash{$key} = join('', @{ $all{$key} });
}
于 2012-07-03T23:20:29.620 回答
0

创建一个子程序:

sub combine_hashes {
  my %result = ();
  my @hashes = @_;
  my $first = shift @hashes;
  for my $element (keys %$first) {
    my $count = 0;
    for my $href (@hashes) {
      $count += (grep {$_ eq $element} (keys %$href));
    }
    if ($count > $#hashes) {
      $result{$element} = $first->{$element};
      $result{$element} .= $_->{$element} for @hashes;
    }
  }
  \%result;
}

并通过以下方式调用它:

my %h = %{combine_hashes(\%h1, \%h2, \%h3)};

...或作为:

my %h = %{combine_hashes(@posHashes)};
于 2012-07-03T23:06:29.677 回答
0

只需创建一个子例程并将其传递给哈希引用

my $combination = combine(@posHashes);

sub combine {
    my @hashes = @_;
    my @keys;
    for my $href (@hashes) {
        push @keys, keys %$href;
    }
    # Insert intersection code here..
    # .....
    my %combo;
    for my $href (@hashes) {
        for my $key (@intersection) {
            $combo{$key} .= $href->{$key};
        }
    }
    return \%combo;
}
于 2012-07-03T23:21:02.973 回答
0

有一个非常简单的解决方案:

sub merge {
    my $first = shift;
    my @hashes = @_;
    my %result;
    KEY:
    for my $key (keys %$first) {
        my $accu = $first->{$key};
        for my $hash (@hashes) {
            next KEY unless exists $hash->{$key};
            $accu .= $hash->{$key};
        }
        $result{$key} = $accu;
    }
    return \%result;
}

您必须使用对哈希的引用来调用它,它也会返回哈希引用,例如:

my $comboHashRef = merge(@posHashes);
于 2012-07-04T21:04:36.570 回答