在perl中将值从一个哈希值复制到另一个哈希值

Ron*_*Ron 13 perl hash

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

例如:

# 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');
Run Code Online (Sandbox Code Playgroud)

一个明显的答案是循环遍历小哈希的键,并复制像这样的值

foreach $key (keys %small_hash) { $small_hash{$key} = $big_hash{$key}; }
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*ley 20

@small_hash{ keys %small_hash } = @big_hash{ keys %small_hash };
Run Code Online (Sandbox Code Playgroud)

  • 此外,"值"的顺序被定义为匹配"键"的顺序,前提是哈希不会在其间发生变化.你可以依靠那一个 (3认同)
  • 您可能正确地假设“keys %hash”的顺序在调用之间不会改变,但是可以保证吗? (2认同)
  • Qtax:根据http://perldoc.perl.org/functions/keys.html密钥的密钥顺序是随机的,但保证**相同的**顺序,直到哈希没有改变... (2认同)

Qta*_*tax 9

这是你可以做到的一种方式:

%small = map { $_, $big{$_} } keys %small;
Run Code Online (Sandbox Code Playgroud)

虽然这与for循环非常相似.

$small{$_} = $big{$_} for keys %small;
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

输出:

A, 1, C, 3, B, 2
Run Code Online (Sandbox Code Playgroud)