17

我有两个哈希值,一个大一个小。所有较小哈希的键都显示在较大的哈希中,但值不同。我想将值从较大的哈希复制到较小的哈希。

例如:

# I have two hashes like so
%big_hash = (A => '1', B => '2', C => '3', D => '4', E => '5');
%small_hash = (A => '0', B => '0', C => '0');
# I want small_hash to get the values of big_hash like this
%small_hash = (A => '1', B => '2', C => '3');

一个明显的答案是遍历小散列的键,并像这样复制值

foreach $key (keys %small_hash) { $small_hash{$key} = $big_hash{$key}; }

有没有更短的方法来做到这一点?

4

3 回答 3

23
@small_hash{ keys %small_hash } = @big_hash{ keys %small_hash };
于 2012-06-13T15:00:38.983 回答
9

这是您可以做到的一种方法:

%small = map { $_, $big{$_} } keys %small;

尽管如此,这与 for 循环非常相似。

$small{$_} = $big{$_} for keys %small;

map 为需要的人提供证明:

my %big = (A => '1', B => '2', C => '3', D => '4', E => '5');
my %small = (A => '0', B => '0', C => '0');

%small = map { $_, $big{$_} } keys %small;

print join ', ', %small;

输出:

A, 1, C, 3, B, 2
于 2012-06-13T15:03:34.567 回答
-2
use strict;
my %source = ( a =>  1, b => 2, c => 3 );
my %target = ( a => -1, x => 7, y => 9 );

# Use a hash slice for the copy operation.
# Note this will clobber existing values.
# Which is probably what you intend here.
@target{ keys %source } = values %source;

for ( sort keys %target ) {
  print $_, "\t", $target{ $_ }, "\n";
}
于 2012-06-13T14:56:52.263 回答