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

时间:2012-06-13 14:49:47

标签: perl hash

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

E.G:

# 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}; }

有更短的方法吗?

3 个答案:

答案 0 :(得分:19)

@small_hash{ keys %small_hash } = @big_hash{ keys %small_hash };

答案 1 :(得分:9)

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

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

Altho与for循环非常相似。

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

map proof对于那些需要的人:

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

答案 2 :(得分:-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";
}