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

时间:2022-09-15 22:23:31

I have two hashes, one big and one small. All of the smaller hash's keys show up in the bigger hash, but the values are different. I want to copy the values from the bigger hash to smaller 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');

An obvious answer would be to loop through the keys of the small hash, and copy over the values like this

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

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

Is there a shorter way to do this?

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

3 个解决方案

#1


19  

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

#2


9  

Here's a way you could do it:

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

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

Altho that's pretty similar to the for loop.

虽然这与for循环很相似。

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

map proof for those that need one:

为需要的人提供地图证明:

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;

Output:

输出:

A, 1, C, 3, B, 2

#3


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

#1


19  

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

#2


9  

Here's a way you could do it:

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

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

Altho that's pretty similar to the for loop.

虽然这与for循环很相似。

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

map proof for those that need one:

为需要的人提供地图证明:

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;

Output:

输出:

A, 1, C, 3, B, 2

#3


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