我有两个哈希,一个大,一个小.所有较小的哈希键都显示在较大的哈希值中,但值不同.我想将值从较大的哈希值复制到较小的哈希值.
例如:
# 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)
这是你可以做到的一种方式:
%small = map { $_, $big{$_} } keys %small;
Run Code Online (Sandbox Code Playgroud)
虽然这与for循环非常相似.
$small{$_} = $big{$_} for keys %small;
Run Code Online (Sandbox Code Playgroud)
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)
| 归档时间: |
|
| 查看次数: |
18356 次 |
| 最近记录: |